【问题标题】:Json response to C# ObjectJson 对 C# 对象的响应
【发布时间】:2017-10-08 22:06:03
【问题描述】:

我正在尝试将 Json 响应转换为 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 由一个 Environments 数组组成,其中只有一个项目。只需解析为Newtonsoft.Json.JsonConverter.DeserializeObject&lt;List&lt;Environment&gt;&gt;(result);

标签: c# json deserialization json2csharp


【解决方案1】:

根据错误,您正在尝试将 JSON 数组反序列化为单个对象。将您的反序列化更新为:

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

【讨论】:

  • 我也尝试将数组用于环境,但它对我有用。公共类环境 { 公共环境 [] 环境 { 获取;放; } } 公共类环境 { 公共字符串 id { 获取;放; } 公共字符串 url { 获取;放; } 公共字符串名称 { 获取;放; } 公共字符串错误 { 获取;放; } 公共 int container_hosts_count { 获取;放; } }
  • @RitujaDange 不要添加名为 Enviroments 的新类。只保留一个类“环境”,但是当你调用反序列化时,声明一个列表。看我的回答。
  • 忽略我之前的评论。它工作..谢谢蒙卡达。
  • @RitujaDange 很高兴听到。您能否通过单击复选标记接受答案。这将帮助其他可能遇到类似问题的人。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-16
  • 1970-01-01
  • 2022-01-15
  • 1970-01-01
  • 2017-10-17
  • 2014-10-30
相关资源
最近更新 更多