简体   繁体   中英

C# throws Unhandled exception error

I get Unhandled exception error when I try to execute this code:

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; }
}

My JSON array:

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

I also used a JSON to C# converter as suggested but it gave me the same RootObject.

Error:

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.

As others have said in the comments, your JSON doesn't match up with the type you're trying to deserialize it to.

If your JSON is right, then you want to deserialize it to a single object:

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

Otherwise, if you're expecting a sequence of these, then your JSON should be something like:

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

Per the exception message:

To fix this error either change the JSON to a JSON array (eg [1,2,3]) or change the deserialized type so that it is a normal .NET type

If you want to deserialize an array, you have to provide an array, which would look like this:

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

Or change the generic type argument to a simple .NET type and not a collection:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM