簡體   English   中英

Json對C#對象的響應

[英]Json response to C# Object

我正在嘗試將Json Response轉換為C#對象。 我的代碼如下。

$ HttpResponseMessage響應= 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.

根據錯誤,您嘗試將JSON數組反序列化為單個對象。 將反序列化更新為:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM