I'm looking how can I add cars to some list by their color. This is json file, and I've used json2csharp to generate classes.
I would like to use better way then checking every single car, and list of their colors. That is horrible if I have 40 cars for example.
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
}
]
}
code
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)
{
}
}
You can achieve it by using System.Reflection
library which adds performance penalty to some extent, but I suppose code isn't performance critical, so you'll be fine.
First of all, you need to create an interface:
public interface ICar
{
List<string> color { get; set;}
}
Car classes should implement that interface:
public class Bmw : ICar
{
public List<string> color { get; set; }
}
After that, you can traverse Car
object by filtering out properties which type implements ICar interface.
RootObject root = JsonConvert.DeserializeObject<RootObject>(json);
foreach (var car in root.cars)
{
var carProperties = car.GetType().GetProperties().Where(p => typeof(ICar).IsAssignableFrom(p.PropertyType));
foreach (var carType in carProperties)
{
var c = carType.GetValue(car);
if (c != null)
{
var colors = ((ICar)c).color;
//Do your thing...
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.