I got stuck on parsing json in incorrect format. I receive the json from third party so it's not possible to change it. I want to skip properties which are not in correct format and return default value instead.
Let's say I have an object with only one integer attribute MyIntAttribute but in real scenario I have more attributes with different types which can be incorrect.
I have this json:
var json = @"[
{ ""MyIntAttribute"": 100 },
{ ""MyIntAttribute"": {
""wrongObject"": 1,
""help"": ""this is wrong""
}}
]";
var collection = JsonConvert.DeserializeObject<List<MyObject>>(json);
My goal is to get collection with two objects. First has value 100 in the attribute since it is correct in json and the second object with default value 0 because there is some nonsense object instead of integer value.
First I tried to use Error handling in JsonSerializerSettings like this:
Error = (sender, args) => { args.ErrorContext.Handled = true; }
It will skip all errors but it doesn't create objects with default value. So I ended up with only one object and the second one with incorect format was not added in the collection.
Then I tried to create custom convertor:
public class ParsingErrorConvertor : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
try
{
return serializer.Deserialize(reader, objectType);
}
catch (Exception e)
{
var t = objectType.IsValueType ? Activator.CreateInstance(objectType) : null;
return t;
}
}
My idea was to use this convertor only for attributes where I want to get default value if something goes wrong but I am still missing something.