JSON.Net 反序列化填充缺失的属性

JSON.Net deserialization populate missing properties

我想将 json 对象反序列化为 c# class 并拥有一个完全填充的默认对象,即使我的 JSON 缺少信息。我试过了

设置对象:

new JsonSerializerSettings {
    DefaultValueHandling = DefaultValueHandling.Populate
    NulValueHandling = NullValueHandling.Include
    ObjectCreationHandling = ObjectCreationHandling.Replace
}

考虑这些 c# classes

public class Root{
    public SpecialProperty name {get;set;}
    public SpecialProperty surname {get;set;}
}

public class SpecialProperty {
    string type {get;set;}
    string value {get;set;}
}

考虑这个 JSON

"Root" : {
    "name" : { 
        "type" : "string",
        "value": "MyFirstname"
    }
}

如何将此 json 反序列化为一个对象,并将可用数据序列化为一个新对象,并将缺少的属性设置为 string.empty

一个解决方案可能是反序列化为对象 X,将默认值存储到对象 Y,然后使用类似 AutoMapper 的方法将非空值从 X 映射到 Y。

最简单的解决方法是将所需的默认值放入构造函数中。

public class Root
{
    public SpecialProperty Name { get; set; }
    public SpecialProperty Surname { get; set; }

    public Root()
    {
        this.Name = SpecialProperty.GetEmptyInstance();
        this.Surname = SpecialProperty.GetEmptyInstance();
    }
}

public class SpecialProperty
{
    public string Name { get; set; }
    public string Type { get; set; }

    public static SpecialProperty GetEmptyInstance()
    {
         return new SpecialProperty
         {
              Name = string.Empty,
              Type = string.Empty
         };
    }
}