Handling extra members during deserialization using Json.net

Suppose I want to deserialize a Json dataset into a Person object.

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

But if I have Json data like the one below:

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

The fields "date of birth" and "place of birth" are not included in the Person class. But I still want to save these fields, so can I use Json.net or other libraries that can store these additional fields in one of the Person fields, such as "unused", as mentioned above?

+7
source share
2 answers

You can 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; } 
+6
source share

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} }; 
+1
source share

All Articles