Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

c#

json.net

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 ?

like image 255
Garnyatar Avatar asked Apr 28 '16 22:04

Garnyatar


1 Answers

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>

like image 76
Alexander Krakovskii Avatar answered Nov 16 '22 18:11

Alexander Krakovskii