使用NewtonSoft将JSON反序列化为.net对象

使用NewtonSoft将JSON反序列化为.net对象

问题描述:

我正在使用Newtonsoft的JSON解析器。使用NewtonSoft将JSON反序列化为.net对象

我得到json的回应。每一次都可能不同。可能的变体:
1.

[ 
     { 
     "type": "typing", 
      "updates": [ 
       { 
        "__type": "qwerty" 
       } 
      ] 
     } 
] 


2.

[ 
    { 
     "token": 1111, 
     "type": "msg", 
     "updates": [   
      { 
       "__type": "asdfg", 
       .... 
      }, 
      { 
       "__type": "asdfg", 
       .... 
      }, 
     ] 
    }, 
    { 
     "type": "typing", 
     "updates": [ 
      { 
       "__type": "qwerty" 
      } 
     ] 
    } 
] 

的问题是,什么样的结构我的对象应该具有分析任何类型的JSON的?

var jToken = JToken.Parse(myResponse); 
var obj = jToken.ToObject<MyObject>(); 

class MyObject 
{ 
// what structure should i have here? 
} 

我会建议寻找一个内置的JSON serializer for .NET。

一(两者的更好)在System.Runtime.Serialization.Json.DataContractJsonSerializer

另一发现是 System.Web.Script.Serialization

Here是如何使用DataContractJsonSerializer的详细描述。

它们不是不同的对象。您的服务返回一个对象数组,其中每个对象包含“更新”数组

var myobj = JsonConvert.DeserializeObject<MyObject[]>(json); 

public class MyObject 
{ 
    public string token; 
    public string type; 
    public Update[] updates; 
} 
public class Update 
{ 
    public string __type; 
}