Click here to Skip to main content
15,880,405 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I am calling API and Response from the API call is as follows. It throws Exception when I used JsonConvert.DeserializeObject<class1>(resp) as because type of the parameters changes for different call. I have used JsonConverter(typeof()) to handle type conversion. But it is not working. How can i handle when type of the parameters of the json response changes?


C#
public class class1
{  
    public double lat { get; set; }
    public double @long { get; set; }
    public int orra { get; set; }
    public List<string> hotelPolicy { get; set; }
}


C#
public class class1
{   
    public object lat { get; set; }
    public object @long { get; set; }
    public double orra { get; set; }
    public List<object> hotelPolicy { get; set; }
}
Posted
Updated 8-Jun-15 21:13pm
v4
Comments
Mathi Mani 9-Jun-15 20:26pm    
Is it the same url returning different type of response or different urls? If you can improve the question by providing more details, you may get an answer.
Member 10874553 10-Jun-15 11:52am    
Same url returns different type of response.

1 solution

I don't think there is a magic silver bullet for this issue.

I would suggest validating the incoming JSON data against one of several pre-defined schemas. If it validates against a particular schema, you can safely call JsonConvert.DeserializeObject<T>() against your DTO class.

JSON Schema Validation[^]

This approach as more performant (it avoids the overhead of raising runtime exceptions)

The other more straight-forward approach would just be to create a 'TryParse' style function, which swallows any exceptions, and call it multiple times, until a valid result is returned ...

C#
public bool TryParseJson<T>(string json, out T value) where T: class, new()
{
    value = new T();
    bool result = false;
    try{
        value = JsonConvert.DeserializeObject<T>(json);
        result = true;
    }catch(Exception)
    {
    }
    return result;
}
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900