JsonPropertyAttribute 中的 JSON.NET NullValueHandling 未按预期工作

Jer*_*acs 8 c# json.net

我有一堂课是这样的:

[JsonObject]
public class Condition
{
    [JsonProperty(PropertyName = "_id")]
    public string Id { get; set; }

    [JsonProperty(PropertyName = "expressions", NullValueHandling = NullValueHandling.Ignore)]
    public IEnumerable<Expression> Expressions { get; set; }

    [JsonProperty(PropertyName = "logical_operation")]
    [JsonConverter(typeof(StringEnumConverter))]
    public LogicOp? LogicalOperation { get; set; }

    [JsonProperty(PropertyName = "_type")]
    [JsonConverter(typeof(AssessmentExpressionTypeConverter))]
    public ExpressionType Type { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

但是,当Expressions属性为 null 时,我会像这样序列化对象:

 var serialized = JsonConvert.SerializeObject(condition, Formatting.Indented);
Run Code Online (Sandbox Code Playgroud)

... Json 字符串的文本包含以下行:

"expressions": null
Run Code Online (Sandbox Code Playgroud)

我的理解是这种情况不应该发生。我究竟做错了什么?

Ebr*_*ram 5

.net API 使用的默认文本序列化器是 System.Text.Json:

https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-customize-properties?pivots=dotnet-6-0

所以如果你想忽略 if null 你可以使用:

[JsonIgnore(条件 = JsonIgnoreCondition.WhenWritingNull)]

例子:

public class Forecast
{
    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingDefault)]
    public DateTime Date { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.Never)]
    public int TemperatureC { get; set; }

    [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)]
    public string? Summary { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个问题已经7年了;当有人问起时,JSON.NET 是事实上的 JSON 序列化器。 (3认同)

小智 0

尝试new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }在 JsonConvert.SerializeObject 方法中作为第三个参数传递。