c# – 无法反序列化JSON数组到类型 – Json.NET

前端之家收集整理的这篇文章主要介绍了c# – 无法反序列化JSON数组到类型 – 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转换为字符串):

[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);
原文链接:https://www.f2er.com/csharp/95669.html

猜你在找的C#相关文章