【问题标题】:Handling extra members when deserializing with Json.net使用 Json.net 反序列化时处理额外的成员
【发布时间】:2015-09-15 06:20:34
【问题描述】:

假设我想将一组 Json 数据反序列化为一个 Person 对象。

class Person
{
    [DataMember]
    string name;
    [DataMember]
    int age;
    [DataMember]
    int height;

    object unused;
}

但如果我有如下 Json 数据:

{
    "name":"Chris",
    "age":100,
    "birthplace":"UK",
    "height":170,
    "birthdate":"08/08/1913",
}

字段“birthdate”和“birthplace”不属于 Person 类。但是我仍然想保留这些字段,那么是否可以使用 Json.net 或其他库来将这些额外字段存储到 Person 的字段之一中,例如上面声明的“未使用”?

【问题讨论】:

    标签: c# json.net


    【解决方案1】:

    您应该可以为此使用 [JsonExtensionData] 属性:http://james.newtonking.com/archive/2013/05/08/json-net-5-0-release-5-defaultsettings-and-extension-data

    void Main()
    {
        var str = "{\r\n    \"name\":\"Chris\",\r\n    \"age\":100,\r\n    \"birthplace\":\"UK\",\r\n    \"height\":170," +
        "\r\n    \"birthdate\":\"08/08/1913\",\r\n}";
        var person = JsonConvert.DeserializeObject<Person>(str);
        Console.WriteLine(person.name);
        Console.WriteLine(person.other["birthplace"]);
    }
    
    class Person
    {
        public string name;
        public int age;
        public int height;
        [JsonExtensionData]
        public IDictionary<string, object> other;
    }
    

    【讨论】:

      【解决方案2】:

      是的,您可以使用JSON.NET

      dynamic dycperson= JsonConvert.DeserializeObject(@"{
      'name':'Chris',
      'age':100,
      'birthplace':'UK',
      'height':170,
      'birthdate':'08/08/1913'}");
      Person person = new Person{
        name = dycperson.name,
        age=dycperson.age,
        height=dycperson.height,
        unused= new {birthplace = dycperson.birthplace, birthdate=dycperson.birthdate}
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2014-09-05
        • 2014-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多