我试图反序列化json对象。它在某一点上工作正常。我有一个Area对象,它包含一个Zone对象数组。
{
"Area":{
"id": "0",
"type": "area",
"size": {
"x": 4.5,
"y": 4.5,
"z": 4.5
},
"position": {
"x": 0,
"y": 0,
"z": 0
},
"rotation": {
"x": 0,
"y": 0,
"z": 0
},
"zones": [
{
"id": "001",
"type": "zone",
"size": {
"x": 1,
"y": 1,
"z": 1
},
"position": {
"x": 1,
"y": 0,
"z": 1
},
"rotation": {
"x": 0,
"y": 0,
"z": 0
}
},
{
"id": "002",
"type": "zone",
"size": {
"x": 1,
"y": 1,
"z": 1
},
"position": {
"x": 3,
"y": 0,
"z": 1
},
"rotation": {
"x": 0,
"y": 0,
"z": 0
}
}
]
}
}
Area
类型反序列化很好,但是,我希望区域数组反序列化为List<Zone>
。我怎样才能做到这一点?
string jsonString = r.ReadToEnd();
JavaScriptSerializer jss = new JavaScriptSerializer();
Area area = jss.Deserialize<Area>(jsonString);
public class Area : AirObject3D
{
public List<Zone> zones;
public List<TouchPoint> touchPoints;
public Area()
{
this.size.X = 4.5;
this.size.Z = 4.5;
}
}
答案 0 :(得分:0)
您只需要正确设置合同即可。为了反序列化列表,您只需将属性类型设置为List<Zone>
(您也可以使用Zone[]
反序列化为数组。)
您的合同可能如下所示:
public class Root
{
public Area Area { get; set; }
}
public class Area
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("type")]
public string Type { get; set; }
[XmlElement("size")]
public Coordinate Size { get; set; }
[XmlElement("position")]
public Coordinate Position { get; set; }
[XmlElement("rotation")]
public Coordinate Rotation { get; set; }
[XmlElement("zones")]
public List<Zone> Zones { get; set; }
}
public class Zone
{
[XmlElement("id")]
public string Id { get; set; }
[XmlElement("type")]
public string Type { get; set; }
[XmlElement("size")]
public Coordinate Size { get; set; }
[XmlElement("position")]
public Coordinate Position { get; set; }
[XmlElement("rotation")]
public Coordinate Rotation { get; set; }
}
public class Coordinate
{
[XmlElement("x")]
public float X { get; set; }
[XmlElement("y")]
public float Y { get; set; }
[XmlElement("z")]
public float Z { get; set; }
}
请注意使用XmlElementAttribute
来确保将小写属性正确地反序列化为大写的C#属性(因为属性应按约定大写)。
在您的数据上使用这样的方法,它可以正确填充所有对象:
JavaScriptSerializer jss = new JavaScriptSerializer();
Root root = jss.Deserialize<Root>(jsonString);
答案 1 :(得分:-6)
你的对象图应该看起来像 -
public class Size
{
public double x { get; set; }
public double y { get; set; }
public double z { get; set; }
}
public class Position
{
public int x { get; set; }
public int y { get; set; }
public int z { get; set; }
}
public class Rotation
{
public int x { get; set; }
public int y { get; set; }
public int z { get; set; }
}
public class Zone
{
public string id { get; set; }
public string type { get; set; }
public Size size { get; set; }
public Position position { get; set; }
public Rotation rotation { get; set; }
}
public class Area
{
public string id { get; set; }
public string type { get; set; }
public Size size { get; set; }
public Position position { get; set; }
public Rotation rotation { get; set; }
public List<Zone> zones { get; set; }
}
public class RootObject
{
public Area Area { get; set; }
}
var o = JsonConvert.DeserializeObject<RootObject>("json");