Reputation: 3506
In my c# app I use json.net
library for working with jsons.
I have situation:
Property:
[JsonProperty("my_test_property_json_key", NullValueHandling = NullValueHandling.Ignore)]
public int[] MyTestProperty{ get; set; }
When my json for this proprty looks like:
[0,1,2,3,4,5]
All works great. But possible situation when I have wrong json value like:
[[0,1,2,3]]
And in this situation I get Exception:
[Newtonsoft.Json.JsonReaderException] = {"Error reading integer. Unexpected token: StartArray. Path 'my_test_property_json_key[0]', line 1, position 3250."}
Correct behavior in this situation should be:
return empty int[]
.
How I can ignore this property, when I have wrong json (property exist, but it is a different type)?
Note: My json is too big (a lot of other properties)- and I can't to recreate it with default data (I can not lose data).
Upvotes: 3
Views: 2137
Reputation: 292695
You can create a custom converter that tries to read an array of integers, and returns an empty array if the data isn't correct:
class MyCustomInt32ArrayConverter : JsonConverter
{
public override object ReadJson(
JsonReader reader,
Type objectType,
Object existingValue,
JsonSerializer serializer)
{
var array = serializer.Deserialize(reader) as JArray;
if (array != null)
{
return array.Where(token => token.Type == JTokenType.Integer)
.Select(token => token.Value<int>())
.ToArray();
}
return new int[0];
}
public override void WriteJson(
JsonWriter writer,
Object value,
JsonSerializer serializer)
{
serializer.Serialize(writer, value);
}
public override bool CanConvert(Type objectType)
{
return objectType == typeof(int[]);
}
}
Just apply the converter to the property using the JsonConverterAttribute
attribute :
[JsonConverterAttribute(typeof(MyCustomInt32ArrayConverter))]
[JsonProperty("my_test_property_json_key", NullValueHandling = NullValueHandling.Ignore)]
public int[] MyTestProperty{ get; set; }
Upvotes: 2