4

I had a property of type IReadOnlyList<RoadLaneDto>. To be compatible elsewhere, I changed it to RoadLaneDto[]. Now, when I deserialize my old data, I get this error:

Newtonsoft.Json.JsonSerializationException : Type specified in JSON 'System.Collections.Generic.List`1[[Asi.Shared.Interfaces.DTOs.Map.RoadLaneDto, Asi.Shared.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]], mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089' is not compatible with 'Asi.Shared.Interfaces.DTOs.Map.RoadLaneDto[], Asi.Shared.Interfaces, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'. Path 'Shapes[0].Lanes.$type', line 78, position 132.

What is the right approach to make these compatible? Can I make the $type a suggestion rather than a requirement? Can I write a custom converter of some kind that would handle this situation?

vendettamit
  • 14,315
  • 2
  • 32
  • 54
Brannon
  • 5,324
  • 4
  • 35
  • 83
  • Can you show some code where you're serializing the object and what is JSON data and respective target types. I think you can extend the JSON serializer to handle such custom mapping. – vendettamit Oct 15 '15 at 23:10

1 Answers1

2

In general I don't recommend serializing collection types, for precisely this reason: you want to be free to change the type of collection (though not necessarily the type of collection item) without serialization problems. If you want to implement a collection-interface-valued property with a specific collection type that differs from Json.NET's defaults, say a HashSet<T> for an ICollection<T>, you can allocate it in the default constructor of the containing class, and Json.NET will use the pre-allocated collection. To serialize only object types and not collection types, set TypeNameHandling = TypeNameHandling.Objects.

That being said, the following converter will swallow type information when deserializing an array of rank 1:

public class IgnoreArrayTypeConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return objectType.IsArray && objectType.GetArrayRank() == 1 && objectType.HasElementType;
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (!CanConvert(objectType))
            throw new JsonSerializationException(string.Format("Invalid type \"{0}\"", objectType));
        if (reader.TokenType == JsonToken.Null)
            return null;
        var token = JToken.Load(reader);
        var itemType = objectType.GetElementType();
        return ToArray(token, itemType, serializer);
    }

    private static object ToArray(JToken token, Type itemType, JsonSerializer serializer)
    {
        if (token == null || token.Type == JTokenType.Null)
            return null;
        else if (token.Type == JTokenType.Array)
        {
            var listType = typeof(List<>).MakeGenericType(itemType);
            var list = (ICollection)token.ToObject(listType, serializer);
            var array = Array.CreateInstance(itemType, list.Count);
            list.CopyTo(array, 0);
            return array;
        }
        else if (token.Type == JTokenType.Object)
        {
            var values = token["$values"];
            if (values == null)
                return null;
            return ToArray(values, itemType, serializer);
        }
        else
        {
            throw new JsonSerializationException("Unknown token type: " + token.ToString());
        }
    }

    public override bool CanWrite { get { return false; } }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }
}

Then you can use it like:

public class RootObject
{
    [JsonProperty(TypeNameHandling = TypeNameHandling.None)] // Do not emit array type information
    [JsonConverter(typeof(IgnoreArrayTypeConverter))]        // Swallow legacy type information
    public string[] Lanes { get; set; }
}

Or, you can use the converter globally in settings and have it swallow type information for all arrays:

    var settings = new JsonSerializerSettings { Converters = new JsonConverter[] { new IgnoreArrayTypeConverter() }, TypeNameHandling = TypeNameHandling.All };

Json.NET does support multidimensional arrays so extending support to arrays of rank > 1 would be possible.

dbc
  • 104,963
  • 20
  • 228
  • 340