我正在用c#构建一个RESTful 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字段。
答案 0 :(得分:0)
将[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; }
}
}
答案 1 :(得分:0)
如果您使用的是 .Net Core WebAPI ,则可以在中间件(Startup.cs)中配置JSON Serializer。
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc()
.AddJsonOptions(options => { options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; });
services.AddAutoMapper();
services.RegisterServices();
}
如果您在 ASP.NET WebAPI 中,请参阅Suppress properties with null value on ASP.NET Web API