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


当前回答

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

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.

其他回答

在我的情况下,使用。net 6这是解决方案:

[JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]

更多信息请点击这里。

在。net Core中,这就容易多了。在你的startup.cs中添加json选项,你可以在那里配置设置。


public void ConfigureServices(IServiceCollection services)

....

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

对于System.Text.Json和.NET Core 3.0,这对我来说是可行的:

var jsonSerializerOptions = new JsonSerializerOptions()
{
    IgnoreNullValues = true
};
var myJson = JsonSerializer.Serialize(myObject, jsonSerializerOptions );

与Json。网

 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 });

结果将是:

{
   "Name": "Bad Boys III",
   "Description": "It's no Bad Boys"
 }

或者像这样设置。

services.AddMvc().AddJsonOptions(options =>
  options.JsonSerializerOptions.IgnoreNullValues = true;
});