简体   繁体   中英

Ignore property when wrong type due deserialization in json.net

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).

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; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM