I have a json string that has multiple class types. I want to be able to parse the json file and also cast the objects dynamically. Example:
object jsonInstanceOfObject = LitJson.JsonMapper.ToObject<Type.GetType(classTypeString)>(jsonString);
Is this even possible?
First, determine the object structure from the json string. And you can do that either yourself by looking at it or you can also use the tool json2csharp.com (also mentioned above by L.B)-its really a handy too. It saves you time. Once you know what the class structure corresponding to the json string is going to be, lets call it T for now, the following will do it.
private async Task<T> ParseJsonToObjectAsync(string jsonValue)
{
var obj = await JsonConvert.DeserializeObjectAsync<T>(jsonValue);
return obj;
}
If you are not using async,you can use this:
private T ParseJsonToObject(string jsonValue)
{
var obj = JsonConvert.DeserializeObject<T>(jsonValue);
return obj;
}
And that json serializer/deserializer is part of Newtonsoft.Json
Hope it helps.
Happy coding :)