Deserializing polymorphic json classes without type information using json.net

后端 未结 5 1083
暖寄归人
暖寄归人 2020-11-21 06:10

This Imgur api call returns a list containing both Gallery Image and Gallery Album classes represented in JSON.

I can\'t see how to

5条回答
  •  春和景丽
    2020-11-21 06:47

    Advanced to Brian Rogers answer. And about "use Serializer.Populate() instead of item.ToObject()". If derived types has contstructors or some of their has own customconverter you must use general way for deserialize JSON. So you must leave work for instantiate new object to NewtonJson. This way you can achieve it in you CustomJsonConverter:

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        ..... YOU Code For Determine Real Type of Json Record .......
    
        // 1. Correct ContractResolver for you derived type
        var contract = serializer.ContractResolver.ResolveContract(DeterminedType);
        if (converter != null && !typeDeserializer.Type.IsAbstract && converter.GetType() == GetType())
        {
            contract.Converter = null; // Clean Wrong Converter grabbed by DefaultContractResolver from you base class for derived class
        }
    
        // Deserialize in general way           
        var jTokenReader = new JTokenReader(jObject);
        var result = serializer.Deserialize(jTokenReader, DeterminedType);
    
        return (result);
    }
    

    This work if you have recursion of objects.

提交回复
热议问题