Handling extra members when deserializing with Json.net

前端 未结 2 1770
半阙折子戏
半阙折子戏 2021-01-05 09:59

Suppose I want to deserialize a set of Json data into a Person object.

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


        
相关标签:
2条回答
  • 2021-01-05 10:44

    Yes,you can do it with 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}
    };
    
    0 讨论(0)
  • 2021-01-05 10:47

    You should be able to use the [JsonExtensionData] attribute for this: 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;
    }
    
    0 讨论(0)
提交回复
热议问题