C#抛出未处理的异常错误

时间:2017-12-07 23:49:29

标签: c# json xamarin.forms

当我尝试执行此代码时,我得到Unhandled exception error

class JsonData
{

    public static async Task RefreshDataAsync()
    {
        Console.WriteLine("Tes2t");
        var uri = new Uri("https://api.myjson.com/bins/****b");
        HttpClient myClient = new HttpClient();

        var response = await myClient.GetAsync(uri);
        if (response.IsSuccessStatusCode)
        {
            var content = await response.Content.ReadAsStringAsync();

            //This line throws the error
            var Items = JsonConvert.DeserializeObject<List<Rootobject>>(content); 

            Console.WriteLine(content);
        }
    }
}

RootObject:

public class Rootobject
{
    public int wantedDegree { get; set; }
    public int currentDegree { get; set; }
}

我的JSON数组:

{
  "wantedDegree": 22,
  "currentDegree": 20
}

我也按照建议使用了JSON到C#转换器,但它给了我相同的RootObject。

错误:

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[Smart_Thermometer.Rootobject]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
12-08 01:10:02.660 I/mono-stdout(11816):
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.
Path 'wantedDegree', line 1, position 16.

2 个答案:

答案 0 :(得分:3)

正如其他人在评论中所说,您的JSON与您尝试将其反序列化的类型不匹配。

如果您的JSON是正确的,那么您希望将其反序列化为单个对象:

var item = JsonConvert.DeserialiseObject<Rootobject>(content);

否则,如果您期望这些序列,那么您的JSON应该是这样的:

[{
  "wantedDegree": 22,
  "currentDegree": 20
}, {
  "wantedDegree": 100,
  "currentDegree": 90
}, {
  "wantedDegree": 5,
  "currentDegree": 3
}]

答案 1 :(得分:2)

根据异常消息:

  

要修复此错误,请将JSON更改为JSON数组(例如[1,2,3])或更改反序列化类型,使其成为正常的.NET类型

如果要反序列化数组,则必须提供一个如下所示的数组:

[
  {
    "wantedDegree": 22,
    "currentDegree": 20
  }
]

或者将泛型类型参数更改为简单的.NET类型而不是集合:

var Items = JsonConvert.DeserializeObject<Rootobject>(content);