假设我想将一组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的某个字段中,例如上面声明的“unused”?
答案 0 :(得分:6)
您应该可以使用[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;
}
答案 1 :(得分:1)
是的,您可以使用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}
};