我使用的是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; }
}

我想仅当Test2List为空时才向Test2List属性添加JsonIgnore()属性。如果它不是空的,那么我想包括它在我的json。


当前回答

.Net 6 - 在Program.cs中添加代码。这将忽略类或记录属性,如果它是空的。

using System.Text.Json.Serialization;

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers()
.AddJsonOptions(opts =>
{
    var enumConverter = new JsonStringEnumConverter();
    opts.JsonSerializerOptions.Converters.Add(enumConverter);
    opts.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingDefault | JsonIgnoreCondition.WhenWritingNull;
});

其他回答

JSON。NET也尊重DataMemberAttribute上的EmitDefaultValue属性,以防你不想将newtonsoft特定的属性添加到你的模型中:

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

@Mrchief / @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

可以在他们的网站(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
// }

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

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

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

在这个在线文档中可以看到。

这里有一个类似的选项,但提供了另一种选择:

public class DefaultJsonSerializer : JsonSerializerSettings
{
    public DefaultJsonSerializer()
    {
        NullValueHandling = NullValueHandling.Ignore;
    }
}

然后,我这样使用它:

JsonConvert.SerializeObject(postObj, new DefaultJsonSerializer());

不同之处在于:

Reduces repeated code by instantiating and configuring JsonSerializerSettings each place it's used. Saves time in configuring every property of every object to be serialized. Still gives other developers flexibility in serialization options, rather than having the property explicitly specified on a reusable object. My use-case is that the code is a 3rd party library and I don't want to force serialization options on developers who would want to reuse my classes. Potential drawbacks are that it's another object that other developers would need to know about, or if your application is small and this approach wouldn't matter for a single serialization.