I have a string that contains a list of fruits. My C# program can't use Fruit directly, it needs to cast them to Banana or Apple. The information about in what to cast them is included in the constructor
attribute in the json.
Note: I'm using JSON.NET.
This is what I want to achieve:
class Fruit{ public string constructor;}
class Banana : Fruit { public int monkey;}
class Apple : Fruit { public string shape;}
string json = @"[
{
""constructor"":""banana"",
""monkey"":1
},
{
""constructor"":""apple"",
""shape"":""round""
}]";
List<Fruit> fruitList = JsonConvert.DeserializeObject<List<Fruit>>(json);
List<Banana> bananaList = new List<Banana>();
List<Apple> appleList = new List<Apple>();
foreach(var fruit in fruitList){
if(fruit.constructor == "banana") bananaList.Add((Banana)fruit); //bug
if(fruit.constructor == "apple") appleList.Add((Apple)fruit); //bug
}
//use bananaList and appleList for stuff
However, I can't do the cast. Is there any way so bananaList contains all objects in the json that has the constructor attributes set to "banana"
and same for appleList?
SOLUTION:
public static string objToJson(object obj) {
return JsonConvert.SerializeObject(obj, Formatting.Indented, new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});
}
public static T jsonToObj<T>(string str) {
return JsonConvert.DeserializeObject<T>(str, new JsonSerializerSettings {
TypeNameHandling = TypeNameHandling.Auto
});
}