使用Json.net反序列化时处理额外的成员 [英] Handling extra members when deserializing with Json.net

查看:68
本文介绍了使用Json.net反序列化时处理额外的成员的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

    object unused;
}

但是,如果我拥有像下面这样的Json数据:

But if I have the Json data like the one below:

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

字段出生日期"和出生地"不属于Person类.但是我仍然想保留这些字段,因此可以使用Json.net或其他可以将这些额外字段存储到Person的字段之一中的库,例如上面声明的未使用"吗?

The fields "birthdate" and "birthplace" are not part of the Person class. But I still want to retain those fields, so is it possible to use Json.net or other libraries that can store those extra fields into one of the fields of Person such as "unused" as declared above?

推荐答案

您应该可以为此使用[JsonExtensionData]属性:

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

这篇关于使用Json.net反序列化时处理额外的成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆