I've run into an interesting problem when converting API data to a C# class in UWP.
I have an API that returns image dimensions, like this:
{
"height": "25",
"width": "25"
}
I also have a class with properties that match the JSON data, generated by json2csharp.com.
public class Image
{
public int height { get; set; }
public Uri url { get; set; }
public int width { get; set; }
}
And I am converting the JSON to a C# class using something like this:
dynamic JsonData = JObject.Parse(JsonString);
Image img = JsonData.ToObject<Image>();
However, if the API does not know the height or width, it returns null instead of an int, like this:
{
"height": null,
"width": "25"
}
This obviously causes an exception to throw, specifically this error message:
Newtonsoft.Json.JsonSerializationException: Error converting value {null} to type 'System.Int32'
Is there some way to work around this or handle this scenario?
intvariables Nullable