0

I spent much time on how to apply a CustomCreationConverter for array item (not the array self) with Json.Net. I tried JsonArrayAttribute, but it's not applicable to a property. Since

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] public sealed class JsonArrayAttribute : JsonContainerAttribute { ... }

My code is as follows, and I want to deserialize a AadlObjectPropertySchema object from a json document:

public class AadlObjectPropertySchema : AadlPropertySchema
{
    // JsonArrayAttribute is not applicable to a property!!
    // [JsonArray(ItemConverterType = typeof(AadlPropertySchemaConverter))]
    public List<AadlPropertySchema> Properties { get; set; } = new List<AadlPropertySchema>();
}

// https://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net-to-deserialize-a-list-of-base
public class AadlPropertySchemaConverter : CustomCreationConverter<AadlPropertySchema>
{

    ...
    public AadlPropertySchema Create(Type objectType, JObject jObject)
    {
        var _kind = (AadlPropertyTypeEnum)Enum.Parse(typeof(AadlPropertyTypeEnum),
            (string)jObject.Property("type"));

        switch (_kind)
        {
            case AadlPropertyTypeEnum.array:
                return new AadlArrayPropertySchema();
            case AadlPropertyTypeEnum.@object:
                return new AadlObjectPropertySchema();
            default:
                return new AadlPropertySchema();
        }
    }
    ...
}
ricky
  • 2,058
  • 4
  • 23
  • 49
  • You need to use `[JsonProperty(ItemConverterType = typeof(AadlObjectPropertySchema))]`. See [Custom json serialization for each item in IEnumerable](https://stackoverflow.com/q/36580519/3744182) or [How to deserialize collection with different types?](https://stackoverflow.com/q/24229735/3744182). – dbc Oct 11 '18 at 13:11
  • thanks,will try later – ricky Oct 11 '18 at 13:21

0 Answers0