2015-11-01 124 views
0

我從我的服務器得到一個json字符串/對象到我的c#客戶端。解析JSON到一個對象

這是JSON:

[ 
{"PrintId":1,"PrintRef":"00000000-0000-0000-0000-000000000000","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}, 
{"PrintId":2,"PrintRef":"39a10cee-7cb3-4ed3-aec2-293761eed96d","Header":"header","TC":"tc","CompanyRef":"00000000-0000-0000-0000-000000000000"}] 

我試圖將其轉換爲對象的列表,像這樣:

var strJson2 = (JObject)JsonConvert.DeserializeObject(strJson); 

public IEnumerable<Model.Print> Get() 
{ 
    var print = new List<Model.Print>(); 

    using (var client = new HttpClient()) 
    { 
     client.BaseAddress = new Uri(Shared.URL); 
     client.DefaultRequestHeaders.Accept.Clear(); 
     client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(Shared.HeaderType)); 
     var response = client.GetAsync(route + "?" + GeneralTags.CUSTOMER_REF + "=" + new Guid().ToString()).Result; 

     if (response.IsSuccessStatusCode) 
     { 
      var strJson = response.Content.ReadAsStringAsync().Result; 
      var strJson2 = (JObject)JsonConvert.DeserializeObject(strJson); 

      List<Model.Print> items = strJson2["data"].Select(x => new Model.Print 
      { 
       CompanyRef = (Guid)x["CompanyRef"], 
       Header = (string)x["Header"], 
       PrintId = (int)x["PrintId"], 
       PrintRef = (Guid)x["PrintRef"], 
       TC = (string)x["TC"] 
      }).ToList();     
     } 
     else 
     { 
      evError(new Exception(String.Format("{0}: {1}", (int)response.StatusCode, response.ReasonPhrase)), ErrorTags.PRINT_GET); 
     } 
    } 
    return print; 
} 

但它在這一行錯誤

這是錯誤:

Unable to cast object of type 'Newtonsoft.Json.Linq.JArray' to type 'Newtonsoft.Json.Linq.JObject'. 
+2

JsonConvert.DeserializeObject <列表>(strJson) – Mate

+0

嗨,這並在使用Raspberry Pi2(Windows 10 IoT作爲操作系統)時不起作用。我忘了添加Raspberry Pi2標籤。 - 對不起 –

回答

2

您的頂級json結構是一個數組而不是一個對象。爲此,你需要轉換爲JArray而不是JObject

var root = (JObject)JsonConvert.DeserializeObject(strJson); 

如果你只是想提取所有的對象,而不是:

var objs = ((JArray)JsonConvert.DeserializeObject(json)).Values<JObject>(); 
+0

yu是個開始。非常感謝你! –