2017-10-08 116 views
0

我想將Json響應轉換爲C#對象。我的代碼如下。Json響應C#對象

$ HttpResponseMessage response = client.GetAsync(TARGETURL).Result;

 HttpContent content = response.Content; 

     // ... Check Status Code         
     Console.WriteLine("Response StatusCode: " + (int)response.StatusCode); 

     // ... Read the string. 
     string result = content.ReadAsStringAsync().Result; 

     Environment myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<Environment>(result); 
     Console.Write(myJsonResponse.id); 

我的JSON對象類是:

public class Environment 
{ 
public string id { get; set; } 
public string url { get; set; } 
public string name { get; set; } 
public string error { get; set; } 
public int container_hosts_count { get; set; } 
} 

結果字符串是:

"[{\"id\":\"23745576\",\"url\":\"https://cloud.mycloud.com/configurations/23745576\",\"name\":\"mycloud Code Screen - Andy Pande\",\"error\":\"\",\"container_hosts_count\":0}]" 

我得到一個錯誤:

Newtonsoft.Json.JsonSerializationException occurred 
    HResult=0x80131500 
    Message=Cannot deserialize the current JSON array (e.g. [1,2,3]) into type 'Environment' because the type requires a JSON object (e.g. {"name":"value"}) to deserialize correctly. 
To fix this error either change the JSON to a JSON object (e.g. {"name":"value"}) or change the deserialized type to an array or a type that implements a collection interface (e.g. ICollection, IList) like List<T> that can be deserialized from a JSON array. JsonArrayAttribute can also be added to the type to force it to deserialize from a JSON array. 
Path '', line 1, position 1. 
+0

你傳入一個數組而不是一個對象(見第一個字符是'''不是''''。 – Dai

+0

您的JSON由一個只有一個項目的'Environment'數組組成。簡單地解析爲'Newtonsoft.Json.JsonConverter.DeserializeObject <列表>(結果);' – nbokmans

回答

2

按照錯誤,你正嘗試將一個JSON數組反序列化爲as單一物體。更新你的反序列化爲:

var myJsonResponse = Newtonsoft.Json.JsonConvert.DeserializeObject<IList<Environment>>(result); 
+0

我嘗試在環境中使用數組,但它的功效對我來說很有用。 public class Environments public environment [] env {get;組; } } public class Environment { public string id {get;組; } public string url {get;組; } public string name {get;組; } 公共字符串錯誤{get;組; } public int container_hosts_count {get;組; } } –

+0

@RitujaDange不添加一個名爲Enviroments的新類。只保留一個類「環境」,但當您調用反序列化時,請聲明一個列表。看到我的答案。 –

+0

忽略我以前的評論。它的工作..謝謝Moncada。 –