简体   繁体   中英

JSON.Net deserialization populate missing properties

I want to deserialize a json object into ac# class and have a completely populated default object even if my JSON is missing the information. I've tried

  • Annotation with [DefaultValue]
  • Creating constructors for the classes
  • Deserializing with a settings object

Settings object:

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

Consider these 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;}
}

Consider this JSON

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

How can I deserialize this json into an object with the available data serialized into a new object and the missing properties, in this case, set to string.empty ?

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

The easiest workaround is putting the default value you want in the constructor.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM