问题
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:
Deserialize your data to a list:
JsonConvert.DeserializeObject<List<RootObject>>(jsr.ReadToEnd());
Instead of implementing
IEnumerable
, implementICollection<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