我反序列化由serialize方法创建的json字符串。 JSON(来自Newtonsoft库)看起来像这样(有点格式化以便更好地阅读):
{"AreaKindList":
[
{"ID":1,"Kind":"Lioncage"},
{"ID":2,"Kind":"Open-Air Enclosure"}
],
"AnimalRaceList":
[
{"ID":1,"Race":"Lion","AllowedAreaKinds":[1]},
{"ID":2,"Race":"Gazelle","AllowedAreaKinds":[2]},
{"ID":3,"Race":"Antelope","AllowedAreaKinds":[2]}
],
"AreaList":
[
{"ID":1,"AreaKindId":1,"Size":2,"AnimalList":
[
{"Name":"Leo","RaceId":1}
]
}
]}
这些课程看起来像这样:
public class Zoo
{
public List<AreaKind> AreaKindList { get; set; }
public List<AnimalRace> AnimalRaceList { get; set; }
public List<Area> AreaList { get; set; }
}
public class AreaKind
{
public int ID { get; private set; }
public string Kind { get; private set; }
public AreaKind(int id, string kind)
{
ID = id;
Kind = kind;
}
}
public class AnimalRace
{
public int ID { get; private set; }
public string Race { get; private set; }
public List<int> AllowedAreaKinds { get; private set; }
public AnimalRace (int id, string race, List<int> areaKindIds)
{
ID = id;
Race = race;
AllowedAreaKinds = areaKindIds;
}
}
public class Area
{
public int ID { get; private set; }
public int AreaKindId { get; set; }
public int Size { get; set; }
public List<Animal> AnimalList { get; set; }
public Area(int size, int areaKindId, int id)
{
ID = id;
AreaKindId = areaKindId;
Size = size;
}
}
正如您所看到的,AnimalRaceList中有一个名为AllowedAreaKinds的数字列表。此时内部只有一个条目。当我使用以下代码反序列化zoo-object时,动物园被完全填充(包括ID为1的动物Leo),但是“List AllowedAreaKinds”被完全设置为“NULL”。为什么呢?
using (StreamReader reader = File.OpenText(Program.JsonFile))
{
JsonSerializer serializer = new JsonSerializer();
Zoo tempZoo = (Zoo) serializer.Deserialize(reader, typeof(Zoo));
}
我甚至更改了Populate()的序列化程序,但结果相同。任何人都知道它可能是什么?