如何使用json.net忽略类中的属性null

我正在使用Json.NET将类序列化为JSON。 json

我有这样的课: 网站

class Test1
{
    [JsonProperty("id")]
    public string ID { get; set; }
    [JsonProperty("label")]
    public string Label { get; set; }
    [JsonProperty("url")]
    public string URL { get; set; }
    [JsonProperty("item")]
    public List<Test2> Test2List { get; set; }
}

我想仅当Test2Listnull时才向Test2List属性添加JsonIgnore()属性。 若是它不为null,那么我想将它包含在个人json中。 url


#1楼

使用JsonProperty属性的替代解决方案: spa

[JsonProperty(NullValueHandling=NullValueHandling.Ignore)]
// or
[JsonProperty("property_name", NullValueHandling=NullValueHandling.Ignore)]

// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]

正如在线文档中所见。 code


#2楼

能够在他们网站上的这个连接中看到(http://james.newtonking.com/archive/2009/10/23/efficient-json-with-json-net-reducing-serialized-json-size.aspx)我支持使用[Default()]指定默认值 orm

取自连接 对象

public class Invoice
{
  public string Company { get; set; }
  public decimal Amount { get; set; }

  // false is default value of bool
  public bool Paid { get; set; }
  // null is default value of nullable
  public DateTime? PaidDate { get; set; }

  // customize default values
  [DefaultValue(30)]
  public int FollowUpDays { get; set; }
  [DefaultValue("")]
  public string FollowUpEmailAddress { get; set; }
}


Invoice invoice = new Invoice
{
  Company = "Acme Ltd.",
  Amount = 50.0m,
  Paid = false,
  FollowUpDays = 30,
  FollowUpEmailAddress = string.Empty,
  PaidDate = null
};

string included = JsonConvert.SerializeObject(invoice,
  Formatting.Indented,
  new JsonSerializerSettings { });

// {
//   "Company": "Acme Ltd.",
//   "Amount": 50.0,
//   "Paid": false,
//   "PaidDate": null,
//   "FollowUpDays": 30,
//   "FollowUpEmailAddress": ""
// }

string ignored = JsonConvert.SerializeObject(invoice,
  Formatting.Indented,
  new JsonSerializerSettings { DefaultValueHandling = DefaultValueHandling.Ignore });

// {
//   "Company": "Acme Ltd.",
//   "Amount": 50.0
// }

#3楼

与@sirthomas的答案相似,JSON.NET也尊重DataMemberAttributeEmitDefaultValue属性ci

[DataMember(Name="property_name", EmitDefaultValue=false)]

若是您已在模型类型中使用[DataContract][DataMember]而且不想添加特定于JSON.NET的属性,则可能须要这样作。 文档


#4楼

您能够这样作来忽略您正在序列化的对象中的全部空值,而后任何空属性都不会出如今JSON中 get

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var myJson = JsonConvert.SerializeObject(myObject, settings);

#5楼

适应@Mychief的/ @ amit的答案,但适用于使用VB的人

Dim JSONOut As String = JsonConvert.SerializeObject(
           myContainerObject, 
           New JsonSerializerSettings With {
                 .NullValueHandling = NullValueHandling.Ignore
               }
  )

请参阅: “对象初始值设定项:命名和匿名类型(Visual Basic)”

https://msdn.microsoft.com/en-us/library/bb385125.aspx

相关文章
相关标签/搜索