将json反序列化为对象列表-无法创建和填充列表类型 [英] Deserializing json into a list of objects - Cannot create and populate list type

查看:511
本文介绍了将json反序列化为对象列表-无法创建和填充列表类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试反序列化json(这是指向它的链接 http://antica.e-sim.org/apiFights.html?battleId=3139&roundId=1 )放入对象列表.

I'm trying to deserialize json (here is link to it http://antica.e-sim.org/apiFights.html?battleId=3139&roundId=1 ) into a list of objects.

这是我的课程:

public class RootObject
    {
        public int Damage { get; set; }
        public int Weapon { get; set; }
        public bool Berserk { get; set; }
        public bool DefenderSide { get; set; }
        public double MilitaryUnitBonus { get; set; }
        public int Citizenship { get; set; }
        public int CitizenId { get; set; }
        public bool LocalizationBonus { get; set; }
        public string Time { get; set; }
        public int MilitaryUnit { get; set; }
    }

    public class Battles: IEnumerable<RootObject>
    {
        public IEnumerable<RootObject> battles { get; set; }
        public IEnumerator<RootObject> GetEnumerator()
        {
            return battles.GetEnumerator();
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return battles.GetEnumerator();
        }
    }

这是我获取json并尝试反序列化的方式:

This is how I get the json and try to deserialize it :

string url = "http://" + serverEsim + ".e-sim.org/apiFights.html?battleId=" +
                                     battles.ElementAt(k).Key + "&roundId=" + i;
                        WebRequest req = WebRequest.Create(url);
                        WebResponse resp = req.GetResponse();
                        StreamReader jsr = new StreamReader(resp.GetResponseStream());
                        Battles battle = JsonConvert.DeserializeObject<Battles>(jsr.ReadToEnd());

当我尝试进行脱硒治疗时,它给了我一个例外:

When I try to desereliaze it gives me an exception :

类型的未处理异常 "Newtonsoft.Json.JsonSerializationException"发生在 Newtonsoft.Json.dll

An unhandled exception of type 'Newtonsoft.Json.JsonSerializationException' occurred in Newtonsoft.Json.dll

其他信息:无法创建和填充列表类型 Project.Battles.路径",第3行,位置1.

Additional information: Cannot create and populate list type Project.Battles. Path '', line 3, position 1.

我该怎么办?

推荐答案

问题是json.net不知道如何向Battles类添加数据.有几种方法可以解决此问题:

The problem is that json.net doesn't know how to add data to your Battles class. There is couple way to fix that:

  1. 将数据反序列化为列表:

  1. Deserialize your data to a list:

JsonConvert.DeserializeObject<List<RootObject>>(jsr.ReadToEnd());

在您的Battles类中实现IEnumerable而不是实现IEnumerable,然后JsonConvert将使用数据正确填充它:

Instead of implementing IEnumerable, implement ICollection<RootObject> in your Battles class, then JsonConvert will properly populate it with data:

public class Battles: ICollection<RootObject>

这篇关于将json反序列化为对象列表-无法创建和填充列表类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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