2
我在看我怎麼能通過它們的顏色添加汽車到一些列表。 這是json文件,我用json2csharp來生成類。JSON到C#反序列化
我想用更好的方法,然後檢查每輛車,並列出他們的顏色。例如,如果我有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。它顯示我寶馬,奧迪...,然後我需要去爲每輛車,但我不喜歡這種方法。 – hurms
@Darjan 不,我不是。它需要爲這個文件完成。 – hurms