简体   繁体   English

如何将json对象反序列化为复杂对象?

[英]How can I deserialize a json object into a complex object?

I'm trying to deserialize a JSON object into an Object with some "object" attribute that may be different each time. 我正在尝试将JSON对象反序列化为具有某些“对象”属性的对象,每次都可能不同。 I have a serializer/deserializer function that works fine when using simple variable types or defined ones. 我有一个序列化器/反序列化器功能,使用简单的变量类型或定义的变量时,它可以正常工作。

I tried to cast the object into the correct class, tried to get the object as dynamic, etc. However, I always get an exception: "Object Reference not established..." 我试图将对象强制转换为正确的类,尝试将对象变为动态等等。但是,我总是得到一个异常:“对象引用未建立...”

Deserialization func: 反序列化函数:

        public static T deserializeJSON<T>(string json)
        {
            T obj = Activator.CreateInstance<T>();
            using (MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
            {
                DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType($
                obj = (T)serializer.ReadObject(ms);
            }
            return obj;
        }

Example object: 示例对象:

 [DataContract]
    class Client
    {
        [DataMember] private string name;
        [DataMember] private string address;
        [DataMember] private string bio;
        [DataMember] private object specific; //WHERE SPECIFIC MAY BE ANY OTHER OBJECT THAT I CAST AFTER DESERIALIZATION
    }

Example object2: 示例对象2:

 [DataContract]
    class Server
    {
        [DataMember] private string name;
        [DataMember] private int value;
    }

The specific attribute may be any other object. 特定属性可以是任何其他对象。 Imagine "specific" attribute is a Server type object; 想象一下“特定”属性是服务器类型对象; The deserialization function loads all attributes well instead of specific that is loaded as an object, but cannot convert it to Server. 反序列化函数可以很好地加载所有属性,而不是作为对象加载的特定属性,但不能将其转换为服务器。

PD: At deserialization moment, I know what class type is the "specific" attribute. PD:在反序列化时刻,我知道什么类类型是“特定”属性。

Thanks! 谢谢!

using latest json.net you can use 使用最新的json.net即可使用

dynamic data = Json.Decode(json);

or 要么

dynamic data = JObject.Parse(json);

and can access data with following code : 并可以使用以下代码访问数据:

data.Date; 
data.Items.Count; 
data.Items[0].Name; 
data.Items[0].Price; 
data.Items[1].Name; 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM