c# - 无法将 JSON 数组反序列化为类型 - Json.NET

标签 c# .net json serialization json.net

我正在尝试将 json 数据反序列化为模型类,但我失败了。这是我所做的:

    public CountryModel GetCountries() {

        using (WebClient client = new WebClient()) {

            var result = client.DownloadString("http://api.worldbank.org/incomeLevels/LIC/countries?format=json");

            var output = JsonConvert.DeserializeObject<List<CountryModel>>(result);

            return output.First();
        }
    }

这是我的模型的样子:

public class CountryModel
{
    public int Page { get; set; }
    public int Pages { get; set; }
    public int Per_Page { get; set; }
    public int Total { get; set; }

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

public class Country
{
    public int Id { get; set; }
    public string Iso2Code { get; set; }
    public string Name { get; set; }
    public Region Region { get; set; }
}

public class Region
{
    public int Id { get; set; }
    public string Value { get; set; }
}

你可以看到我在这里得到的 Json:http://api.worldbank.org/incomeLevels/LIC/countries?format=json

这是我得到的错误:

Cannot deserialize JSON array into type 'Mvc4AsyncSample.Models.CountryModel'. Line 1, position 1.

最佳答案

你必须写一个自定义的JsonConverter:

    public class CountryModelConverter : JsonConverter
    {

        public override bool CanConvert(Type objectType)
        {
            if (objectType == typeof(CountryModel))
            {
                return true;
            }

            return false;
        }

        public override object ReadJson(JsonReader reader, Type objectType
            , object existingValue, JsonSerializer serializer)
        {
            reader.Read(); //start array
            //reader.Read(); //start object
            JObject obj = (JObject)serializer.Deserialize(reader);

            //{"page":1,"pages":1,"per_page":"50","total":35}
            var model = new CountryModel();

            model.Page = Convert.ToInt32(((JValue)obj["page"]).Value);
            model.Pages = Convert.ToInt32(((JValue)obj["pages"]).Value);
            model.Per_Page = Int32.Parse((string) ((JValue)obj["per_page"]).Value);
            model.Total = Convert.ToInt32(((JValue)obj["total"]).Value);

            reader.Read(); //end object

            model.Countries = serializer.Deserialize<List<Country>>(reader);

            reader.Read(); //end array

            return model;
        }

        public override void WriteJson(JsonWriter writer, object value
            , JsonSerializer serializer)
        {
            throw new NotImplementedException();
        }
    }

并使用该转换器标记 CountryModel(我还必须将一些 int 转换为 string):

    [JsonConverter(typeof(CountryModelConverter))]
    public class CountryModel
    {
        public int Page { get; set; }
        public int Pages { get; set; }
        public int Per_Page { get; set; }
        public int Total { get; set; }

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

    public class Country
    {
        public string Id { get; set; }
        public string Iso2Code { get; set; }
        public string Name { get; set; }
        public Region Region { get; set; }
    }

    public class Region
    {
        public string Id { get; set; }
        public string Value { get; set; }
    }

那么你应该能够像这样反序列化:

var output = JsonConvert.DeserializeObject<CountryModel>(result);

关于c# - 无法将 JSON 数组反序列化为类型 - Json.NET,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9452901/

相关文章:

javascript - 在 JSON 中查找给定键的值并使用 javascript 更改该值

android - 提高json解析性能

c# - 如何打开服务属性对话框

c# - 根据返回类型Interface限制Web API序列化的模型数据字段

c# - 有没有更好的方法来限制高吞吐量作业?

c# - 在 Visual Studio 中测试简单的 C# 代码表达式

java - 按某种模式过滤 pojo 属性

c# - 为什么 DefaultStyleKey 不更改我的子类的默认样式?

c# - 一个类怎么可能没有构造函数呢?

.net - 为什么使用retrieve <entity>后无法访问单个实体的属性?