2017-10-08 115 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。 –