I have a simple API which result in different types of config for different tasks, So I am looking to find a way to parse the response dynamically using if/else. But for some reason, the config is not deserialized because that's a string already and Serialize()
do it again.
So, the JsonConvert.DeserializeObject<typeAhandler>(jsonString)
doesn't work then.
Here is my code :
void Main()
{
var json = new ApiResponse {name = "name1", type = "a", config = "{'title' : 'hello world!', 'id' : 1}"};
var jsonString = JsonConvert.SerializeObject(json);
Console.WriteLine(jsonString);
if (json.type == "a")
{
var handler = JsonConvert.DeserializeObject<typeAhandler>(jsonString);
handler.Dump();
}
else if(json.type == "b")
{
var handler = JsonConvert.DeserializeObject<typeBhandler>(jsonString);
handler.Dump();
}
}
public class ApiResponse
{
public string name { get; set; }
public string type {get; set;}
public string config {get;set;}
}
// Type A Handler
public class typeAhandler
{
public string name { get; set; }
public typeAconfig config { get; set; }
}
public class typeAconfig
{
public string title { get; set; }
public int id { get; set; }
}
// Type B Handler
public class typeBhandler
{
public string name { get; set; }
public typeBconfig config { get; set; }
}
public class typeBconfig
{
public string[] items { get; set; }
}