我有一堂课是这样的:
[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)
我的理解是这种情况不应该发生。我究竟做错了什么?
.net API 使用的默认文本序列化器是 System.Text.Json:
所以如果你想忽略 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)
小智 0
尝试new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }在 JsonConvert.SerializeObject 方法中作为第三个参数传递。
| 归档时间: |
|
| 查看次数: |
7810 次 |
| 最近记录: |