无法反序列化JSON数组类型 - Json.NET [英] Cannot deserialize JSON array into type - Json.NET

查看:270
本文介绍了无法反序列化JSON数组类型 - Json.NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化JSON数据转换成一个模型类,但我失败了。这是我做的:

 公共CountryModel GetCountries(){

        使用(Web客户端的客户端=新的Web客户端()){

            VAR的结果= client.DownloadString(http://api.worldbank.org/incomeLevels/LIC/countries?format=json);

            无功输出= JsonConvert.DeserializeObject<列表< CountryModel>>(结果);

            返回output.First();
        }
    }
 

这是我的模式是这样的:

 公共类CountryModel
{
    公众诠释页{获得;组; }
    公众诠释页{获得;组; }
    公众诠释Per_Page {获得;组; }
    公众诠释共{获得;组; }

    公开名单<国家>国家{获得;组; }
}

公共类国家
{
    公众诠释编号{获得;组; }
    公共字符串ISO2 code {获得;组; }
    公共字符串名称{;组; }
    公共区域地区{获得;组; }
}

公共类地区
{
    公众诠释编号{获得;组; }
    公共字符串值{获得;组; }
}
 

您可以看到的Json我得到这里:的http:// API。 worldbank.org/incomeLevels/LIC/countries?format=json

这是我的错误:

  

无法反序列化JSON数组类型Mvc4AsyncSample.Models.CountryModel。行1,位置1。

解决方案

您必须编写自定义的 JsonConverter

 公共类CountryModelConverter:JsonConverter
    {

        公众覆盖布尔CanConvert(类型的objectType)
        {
            如果(的objectType == typeof运算(CountryModel))
            {
                返回true;
            }

            返回false;
        }

        公众覆盖对象ReadJson(JsonReader读者,类型的objectType
            ,反对existingValue,JsonSerializer串行)
        {
            reader.Read(); //启动阵列
            //reader.Read(); //启动对象
            JObject OBJ =(JObject)serializer.Deserialize(读卡器);

            // {页面:1,页:1,per_page:50,共:35}
            VAR模型=新CountryModel();

            model.Page = Convert.ToInt32(((JValue)OBJ [页])值。);
            model.Pages = Convert.ToInt32(((JValue)OBJ [页])值);
            model.Per_Page = Int32.Parse((字符串)((JValue)OBJ [per_page])值。);
            model.Total = Convert.ToInt32(((JValue)OBJ [总])值。);

            reader.Read(); //结束对象

            model.Countries = serializer.Deserialize<列表<国家>>(读卡器);

            reader.Read(); //端阵列

            回归模型;
        }

        公众覆盖无效WriteJson(JsonWriter作家,对象值
            ,JsonSerializer串行)
        {
            抛出新的NotImplementedException();
        }
    }
 

和标签 CountryModel 与转换器(我也不得不改用一些 INT 字符串):

  [JsonConverter(typeof运算(CountryModelConverter))]
    公共类CountryModel
    {
        公众诠释页{获得;组; }
        公众诠释页{获得;组; }
        公众诠释Per_Page {获得;组; }
        公众诠释共{获得;组; }

        公开名单<国家>国家{获得;组; }
    }

    公共类国家
    {
        公共字符串ID {获得;组; }
        公共字符串ISO2 code {获得;组; }
        公共字符串名称{;组; }
        公共区域地区{获得;组; }
    }

    公共类地区
    {
        公共字符串ID {获得;组; }
        公共字符串值{获得;组; }
    }
 

然后,你应该能够反序列化是这样的:

 无功输出= JsonConvert.DeserializeObject< CountryModel>(结果);
 

I am trying to deserialize a json data into a model class but I am failing. Here is what I do:

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

This is how my model looks like:

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

You can see the Json I am getting here: http://api.worldbank.org/incomeLevels/LIC/countries?format=json

This is the error I get:

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

解决方案

You have to write a custom 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();
        }
    }

And tag the CountryModel with that converter (I also had to switch some int to 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; }
    }

Then you should be able to deserialize like this:

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

这篇关于无法反序列化JSON数组类型 - Json.NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆