我正在C#中建立一个安息的Web服务。
所以我已经构建了这样的DTO模型:
namespace WebService.Models
{
[DataContract(Name = "VitalSigns")]
public class VitalSignsDTO
{
[DataMember(Name = "id", Order = 1)]
public int id { get; set; }
[DataMember(Name = "name", Order = 2)]
public string name { get; set; }
[DataMember(Name = "valore", Order = 3)]
public string valore { get; set; }
[DataMember(Name = "dataOra", Order = 3)]
public DateTime? dataOra { get; set; }
}
}
现在,这是JSON的响应:
{
"id": 1,
"name": "Altezza corporea",
"valore": null,
"dataOra": null
},
{
"id": 2,
"name": "Peso corporeo",
"valore": null,
"dataOra": null
}
现在,我想知道,如果可以使用没有值的隐藏的Valore和Dataora字段。
使用 [JsonIgnore]
属性。
namespace WebService.Models
{
[DataContract(Name = "VitalSigns")]
public class VitalSignsDTO
{
[DataMember(Name = "id", Order = 1)]
public int id { get; set; }
[DataMember(Name = "name", Order = 2)]
public string name { get; set; }
[JsonIgnore]
[DataMember(Name = "valore", Order = 3)]
public string valore { get; set; }
[JsonIgnore]
[DataMember(Name = "dataOra", Order = 3)]
public DateTime? dataOra { get; set; }
}
}
如果您在 .net core webapi 中,则可以在中间件中配置JSON Serializer(startup.cs(。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; });
services.AddAutoMapper();
services.RegisterServices();
}
如果您在 ASP.NET WebApi 中,请在ASP.NET Web API上使用null值抑制属性