Reputation: 2585
I have a json feed that can be seen here.
I properly mapped the enitre json into classes by defining each structure. Just stuck at one place. If you see the json and search for the property headliners
which is an array, it has a property image
which is an object. So I created a classes to map
public class HeadeLiners
{
public Image Image { get; set; }
}
public class Image
{
public ImageSize Jumbo{ get; set; }
}
public class ImageSize
{
public string Path{ get; set; }
public int Width{ get; set; }
public int Height{ get; set; }
}
But what happen if in response headliners
property there is no image found it returns an array which breaks the mapping. and it make sense. I am not sure how to handle this, any please suggest
Upvotes: 3
Views: 221
Reputation: 17405
Indeed, that is one weird use of JSON.
Here's what you can do:
var settings = new JsonSerializerSettings();
settings.Error += (obj, errorArgs) =>
{
if ("image".Equals(errorArgs.ErrorContext.Member))
{
errorArgs.ErrorContext.Handled = true;
}
};
var test = JsonConvert.DeserializeObject<Test>(json, settings);
By handling the Error
event, you can selectively ignore these kinds of errors. If you ignore this error at this particular location (checking just the member name might just do it) your Image
property remains null
, which is probably what you want here.
Upvotes: 1