【问题标题】:JsonConvert - Force MissingMember to nullJsonConvert - 强制 MissingMember 为空
【发布时间】:2019-09-18 04:13:09
【问题描述】:

我有一个FilterDto 类,用于将过滤器信息发送到我的客户端应用程序。 例如:

public class FilterDto
{
    public string Code { get; set; } = "Default code";
    public string Description { get; set; }
}

这个序列化如下:

[
    {
        field: 'Code',
        type: 'text',
        defaultValue: 'Default code'
    },
    {
        field: 'Description ',
        type: 'text',
        defaultValue: null
    }
]

因此,在我的客户端中,我可以为给定字段呈现两个 input text。当用户过滤返回的 JSON 是这样的:

{
    Code: 'code to filter',
    Description: 'description to filter'
}

然后我像这样反序列化它:

var filter = JsonConvert.DeserializeObject(json, typeof(FilterDto));
Console.WriteLine(filter.Code); // code to filter

问题是,如果用户决定删除代码的默认值,在上面的示例中,我将拥有 JSON:

{
    Description: 'description to filter'
}

反序列化时,我将拥有:

var filter = JsonConvert.DeserializeObject(json, typeof(FilterDto));
Console.WriteLine(filter.Code); // Default code

当 JSON 中缺少 Code 时,是否可以将其设置为 null 而不是其默认值?

谢谢

【问题讨论】:

    标签: c# serialization .net-core json.net


    【解决方案1】:

    试试这个:

            public class FilterDto
            {
                private const string DefaultValue = "Default code";
    
                [OnDeserialized]
                internal void OnDeserializedMethod(StreamingContext context)
                {
                    if (Code == DefaultValue)
                    {
                        Code = null; //set to null or string.empty
                    }
                }
    
                public string Code { get; set; } = DefaultValue;
                public string Description { get; set; }
            }
    

    【讨论】:

    • 这可行,但我期待更通用的东西......无需为我拥有的每个FilterDto 编写该逻辑......目前我正在使用一些反射将值设置为默认值,如果它们不存在于 json 中...
    【解决方案2】:

    我相信,你所看到的已经解释了here

    .

    另外,如果属性不存在,你可以添加

    [JsonProperty(PropertyName ="defaultValue", NullValueHandling = NullValueHandling.Include, DefaultValueHandling = DefaultValueHandling.Populate)]
    

    另外,这篇文章将告诉你如何覆盖空值:here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多