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

Ami*_*mit 497 c# json.net

我正在使用Json.NET将类序列化为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; }
}
Run Code Online (Sandbox Code Playgroud)

我想将添加JsonIgnore()属性,Test2List只有当财产Test2Listnull.如果它不为null,那么我想将它包含在我的json中.

sir*_*mas 853

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

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

// or for all properties in a class
[JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)]
Run Code Online (Sandbox Code Playgroud)

正如在线文档中所见.

  • @Sergey这取决于你的用例.如果您只想将它​​用于特定属性(如问题中所述),那么这是正确的答案.如果需要全局答案,则应在JsonSerializer中设置该属性. (95认同)
  • 接受的答案更好,因为它不会使用Json.net属性污染您的类. (17认同)
  • @Destek 您需要将引用类型字段设为可空,然后它们将不会使用属性或设置进行序列化。 (4认同)
  • 为了避免使用许多属性“污染”您的类,您还可以在“[JsonObject]”上分配处理规则,但请注意属性名称不同。[编辑后的答案] (4认同)
  • 嗯,无法让 [JsonObject(ItemNullValueHandling = NullValueHandling.Ignore)] 工作:找不到类型或命名空间名称“ItemNullValueHandling”。我确实添加了 using Newtonsoft.Json.Serialization;... (2认同)

Mrc*_*ief 643

根据James Newton King的说法:如果你自己创建序列化程序而不是使用JavaScriptConvert ,那么你可以设置一个NullValueHandling属性来忽略它.

这是一个示例:

JsonSerializer _jsonWriter = new JsonSerializer {
                                 NullValueHandling = NullValueHandling.Ignore
                             };
Run Code Online (Sandbox Code Playgroud)

或者,正如@amit所建议的那样

JsonConvert.SerializeObject(myObject, 
                            Newtonsoft.Json.Formatting.None, 
                            new JsonSerializerSettings { 
                                NullValueHandling = NullValueHandling.Ignore
                            });
Run Code Online (Sandbox Code Playgroud)

  • 这适用:JsonConvert.SerializeObject(myObject,Newtonsoft.Json.Formatting.None,new JsonSerializerSettings {NullValueHandling = NullValueHandling.Ignore}); (152认同)
  • 一件重要的事情 - 它仅适用于具体类(人员、帐户等)。当我用字典尝试这个时,它不起作用 (2认同)
  • 编写答案时,JSON.Net甚至不支持动态对象。:)目前,您可以使用自定义转换器进行出价。 (2认同)

Tob*_*s J 56

类似@ sirthomas的回答,也JSON.NET尊重EmitDefaultValue特性DataMemberAttribute:

[DataMember(Name="property_name", EmitDefaultValue=false)]
Run Code Online (Sandbox Code Playgroud)

如果您已经在模型类型中使用[DataContract]并且[DataMember]不想添加特定于JSON.NET的属性,则可能需要这样做.

  • 这在.Net Core中不起作用。推荐@sirthomas答案:使用[JsonProperty(NullValueHandling = NullValueHandling.Ignore)] (2认同)

Bru*_*ner 32

就我而言,使用 .NET 6 的解决方案是:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
Run Code Online (Sandbox Code Playgroud)

更多信息请点击这里

  • 谢谢你 - 许多其他答案都假设使用 JSON.net,这不再是真正必要的了。 (3认同)
  • 同上,对于新的 .NET 用户来说这个答案应该要高得多 (2认同)

Er *_*tel 31

你可以写: [JsonProperty("property_name",DefaultValueHandling = DefaultValueHandling.Ignore)]

它还负责不使用默认值(不仅为null)序列化属性.例如,它可用于枚举.

  • 你可以在答案中解释一下吗?乍一看,它看起来一样,现在你已经提到过,它没有说明这与其他答案/它如何恭维它有何不同. (4认同)
  • 这和sirthomas的答案完全一样,为什么要添加它? (3认同)
  • 对于您的类型信息,DefaultValueHandling和NullValueHandling之间存在差异...... (2认同)
  • 我想这就是我想要的。对某些属性的特定处理,而不是全部。 (2认同)

Chr*_*row 22

您可以这样做来忽略您正在序列化的对象中的所有空值,然后任何空属性都不会出现在JSON中

JsonSerializerSettings settings = new JsonSerializerSettings();
settings.NullValueHandling = NullValueHandling.Ignore;
var myJson = JsonConvert.SerializeObject(myObject, settings);
Run Code Online (Sandbox Code Playgroud)


Mic*_*ein 12

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

取自链接

   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
// }
Run Code Online (Sandbox Code Playgroud)


Raf*_*afy 10

使用Json.NET

 public class Movie
 {
            public string Name { get; set; }
            public string Description { get; set; }
            public string Classification { get; set; }
            public string Studio { get; set; }
            public DateTime? ReleaseDate { get; set; }
            public List<string> ReleaseCountries { get; set; }
 }

 Movie movie = new Movie();
 movie.Name = "Bad Boys III";
 movie.Description = "It's no Bad Boys";

 string ignored = JsonConvert.SerializeObject(movie,
            Formatting.Indented,
            new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
Run Code Online (Sandbox Code Playgroud)

结果将是:

{
   "Name": "Bad Boys III",
   "Description": "It's no Bad Boys"
 }
Run Code Online (Sandbox Code Playgroud)


Pas*_* R. 10

对于System.Text.Json.NET Core 3.0,这对我有用:

var jsonSerializerOptions = new JsonSerializerOptions()
{
    IgnoreNullValues = true
};
var myJson = JsonSerializer.Serialize(myObject, jsonSerializerOptions );
Run Code Online (Sandbox Code Playgroud)

  • IgnoreNullValues 显然已被弃用,您现在可以使用: `DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull` (4认同)

Hiz*_*zzy 5

在 .Net Core 中,这现在更容易了。在您的 startup.cs 中只需添加 json 选项,您就可以在那里配置设置。


public void ConfigureServices(IServiceCollection services)

....

services.AddMvc().AddJsonOptions(options =>
{
   options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;               
});

Run Code Online (Sandbox Code Playgroud)