I’m using an API and I’m not 100% sure of the types (and that can’t be changed, unfortunately). I’m using the method ‘DeserializeObject’ from the NewtonSoft.Json namespace ‘JsonConvert’ type.
Is there a way to deserialize the things that I have defined and skip the errors?
For example, let’s say I have the following JSON object:
{
"name": "John Smith",
"age": 30,
"city": "New York"
}
And the C# object I’ll deserialize it into will be:
// Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(myJsonResponse);
public class Root
{
public string name { get; set; }
public int age { get; set; }
public string city { get; set; }
}
However, let’s say the age comes as a string, but I don’t know it may come as a string and thus I can’t use the JsonConverter method. That’d end in an error.
Is there a way to handle the error and deserialize the name property and the city property?
2
Answers
Try using this code example
If you use Newtonsoft.Json, in this case "age":"30" will be working too
But you can’t create one code to held properly the exceptions for all properties. For example, in the case "age":"" or "age":null , I would create a json costructor