我的模型类如下:
public class Details
{
public Customer customer{ get; set; }
public List<Point> points{ get; set; }
public List<Color> colors { get; set; }
}
以下是填充模型的方法: -
Details details = new Details();
var info = gets data from service
foreach (var item in info)
{
Points p = new Points();
p.value = item.value;
details.points= new List<Dial>();
fusionChartDetails.points.Add(p);
}
Color c1 = new Color();
c1.code = "#1";
Color c2 = new Color();
c2.code = "#2";
Color c3 = new Color();
c3.code = "#3";
details.colors = new List<Color>();
details.colors.Add(c1);
details.colors.Add(c2);
details.colors.Add(c3);
}
var final=JsonConvert.SerializeObject<details>();
预期:json
{
"customer": {
"caption": "Customer 1"
},
"colors": {
"color": [
{
"code": "#1"
},
{
"code": "#2"
},
{
"code": "#3"
}
]
},
"points": {
"point": [
{
"value": "10"
}
]
} }
但是得到这个:
{
"customer": {
"caption": "Customer 1"
},
"colors": [
{
"code": "#1"
},
{
"code": "#2"
},
{
"code": "#3"
}
],
"points": [
{
"value": "10"
}
]
}
不同之处在于内点和颜色对象在我的json结构中没有被构造。如何做到这一点?
答案 0 :(得分:3)
您还需要几个额外的课程:
public class Details
{
public Customer customer { get; set; }
public Points points { get; set; }
public Colors colors { get; set; }
}
public class Points
{
public List<Point> point { get; set; }
}
public class Color
{
public List<Color> color { get; set; }
}
然后像这样填充:
details.points = new Points
{
point = new List<Point>,
};
details.points.point.add(p1);
details.points.point.add(p2);
details.points.point.add(p3);
...
details.colors = new Colors
{
color = new List<Color>(),
};
details.colors.color.Add(c1);
details.colors.color.Add(c2);
details.colors.color.Add(c3);