这个 JSON 文件有什么问题?不能反序列化

What is wrong with this JSON file? Can't be deserialized

我有一个 JSON 文件有问题,该文件是国家/地区对象列表,如下所示:

{
    "Countries": [
        {
            "Code": "AFG",
            "Name": "Afghanistan",
            "Population": 38928346
        },
        {
            "Code": "ALA",
            "Name": "Åland Islands",
            "Population": 28007
        },
        {
            "Code": "ALB",
            "Name": "Albania",
            "Population": 2877797
        },
        {
            "Code": "DZA",
            "Name": "Algeria",
            "Population": 43851044
        },
        {
            "Code": "ASM",
            "Name": "American Samoa",
            "Population": 55191
        }
    ]
}

我正在尝试使用此代码读取它并将其反序列化为一个 List 对象:

Stream? countriesResourceStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyProject.Countries.json");

if (countriesResourceStream == null)
{
    return;
}

var countries = new List<Country>();

using (StreamReader reader = new StreamReader(countriesResourceStream))
{
    var serializer = new JsonSerializer();
    countries = serializer.Deserialize<List<Country>>(new JsonTextReader(reader));
}

但是 serializer.Deserialize 方法抛出异常:

'Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List`1[MyProject.Models.EntityFramework.Country]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly. 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) 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.

我的 JSON 有什么问题?我已经尝试过 Newtonsoft 和 System.Text.Json.

问题是您的 JSON 不代表国家列表,它代表 包含 国家列表的对象。你需要另一个 class:

class CountryListContainer
{
    public List<Country> Countries { get; set; }
}

反序列化到容器 class 然后你可以从中得到你的国家列表:

using (StreamReader streamReader = new StreamReader(countriesResourceStream))
using (JsonTextReader jsonReader = new JsonTextReader(streamReader))
{
    var serializer = new JsonSerializer();
    countries = serializer.Deserialize<CountryListContainer>(jsonReader).Countries;
}

Fiddle: https://dotnetfiddle.net/5DM4il


或者,您可以按照@Charles Duffy 在评论中的建议更改您的JSON。如果 JSON 看起来像这样(没有外部对象),那么您现有的代码就可以工作:

[
  {
    "Code": "AFG",
    "Name": "Afghanistan",
    "Population": 38928346
  },
  {
    "Code": "ALA",
    "Name": "Åland Islands",
    "Population": 28007
  },
  {
    "Code": "ALB",
    "Name": "Albania",
    "Population": 2877797
  },
  {
    "Code": "DZA",
    "Name": "Algeria",
    "Population": 43851044
  },
  {
    "Code": "ASM",
    "Name": "American Samoa",
    "Population": 55191
  }
]

Fiddle: https://dotnetfiddle.net/gMHhcX