Deserializing json into a list of objects - Cannot create and populate list type [duplicate]

假装没事ソ 提交于 2020-01-02 12:26:50

问题


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.

This is my class:

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

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 :

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

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

What do I do wrong ?


回答1:


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. Deserialize your data to a list:

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

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

    public class Battles: ICollection<RootObject>



来源:https://stackoverflow.com/questions/36926867/deserializing-json-into-a-list-of-objects-cannot-create-and-populate-list-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!