2012-02-13 108 views
1

我正在使用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? 
} 

回答

2

它們不是不同的對象。您的服務返回一個對象數組,其中每個對象包含「更新」數組

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

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