【发布时间】:2017-03-25 19:07:09
【问题描述】:
我正在寻找如何按颜色将汽车添加到某个列表中。 这是json文件,我用json2csharp生成类。
我想用更好的方法检查每辆车,并列出它们的颜色。例如,如果我有 40 辆汽车,那就太可怕了。
json
{
"cars":[
{
"bmw":{
"color":[
"blue",
"red"
]
},
"price":5
},
{
"audi":{
"color":[
"blue",
"yellow",
"white"
]
},
"price":7
},
{
"nil":"nil"
},
{
"peugeot":{
"color":[
"blue",
"red",
"yellow",
"orange"
]
},
"price":12
},
{
"ferrari":{
"color":[
"blue",
"yellow",
"orange"
]
},
"price":12
}
]
}
代码
public class Bmw
{
public List<string> color { get; set; }
}
public class Audi
{
public List<string> color { get; set; }
}
public class Peugeot
{
public List<string> color { get; set; }
}
public class Ferrari
{
public List<string> color { get; set; }
}
public class Car
{
public Bmw bmw { get; set; }
public int price { get; set; }
public Audi audi { get; set; }
public string nil { get; set; }
public Peugeot peugeot { get; set; }
public Ferrari ferrari { get; set; }
}
public class RootObject
{
public List<Car> cars { get; set; }
}
using (StreamReader r = new StreamReader("carDB.json"))
{
string json = r.ReadToEnd();
RootObject car = JsonConvert.DeserializeObject<RootObject>(json);
foreach(Car c in car.cars)
{
}
}
【问题讨论】:
-
你能改变json结构吗?
-
@MickyD 好吧,我在这个 foreach 循环中,当我去 c。它向我展示了宝马、奥迪……,然后我需要为每辆车都去,但我不喜欢这种方法。
-
@Darjan 不,我不是。需要为此文件完成。
-
感谢您编辑问题以添加代码。 +1 :)