簡體   English   中英

C#引發未處理的異常錯誤

[英]C# throws Unhandled exception error

嘗試執行以下代碼時, 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);
        }
    }
}

根對象:

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.

就像其他人在評論中說的那樣,您的JSON與您要反序列化的類型不匹配。

如果您的JSON是正確的,那么您想將其反序列化為單個對象:

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

否則,如果您期望這些序列,那么您的JSON應該類似於:

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

根據異常消息:

要解決此錯誤,可以將JSON更改為JSON數組(例如[1,2,3]),也可以更改反序列化類型,使其成為普通的.NET類型。

如果要反序列化數組,則必須提供一個數組,如下所示:

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

或將通用類型參數更改為簡單的.NET類型而不是集合:

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

暫無
暫無

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

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