Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

c# - Property-based type resolution in JSON.NET

Is it possible to override the type resolution using JSON.NET based on a property of the JSON object? Based on existing APIs, it looks like I need a way of accepting a JsonPropertyCollection and returning the Type to be created.

NOTE: I'm aware of the TypeNameHandling attribute, but that adds a $type property. I do not have control over the source JSON.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It would appear that this is handled by creating a custom JsonConverter and adding it to JsonSerializerSettings.Converters before deserialisation.

nonplus has left a handy sample on the JSON.NET discussions board on Codeplex. I've modified the sample to return custom Type and deferring to the default creation mechanism, rather than creating the object instance on the spot.

abstract class JsonCreationConverter<T> : JsonConverter
{
    /// <summary>
    /// Create an instance of objectType, based properties in the JSON object
    /// </summary>
    protected abstract Type GetType(Type objectType, JObject jObject);

    public override bool CanConvert(Type objectType)
    {
        return typeof(T).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, 
        object existingValue, JsonSerializer serializer)
    {
        JObject jObject = JObject.Load(reader);

        Type targetType = GetType(objectType, jObject);

        // TODO: Change this to the Json.Net-built-in way of creating instances
        object target = Activator.CreateInstance(targetType);

        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }
}

And here is the example usage (also updated as mentioned above):

class VehicleConverter : JsonCreationConverter<Vehicle>
{
    protected override Type GetType(Type objectType, JObject jObject)
    {
        var type = (string)jObject.Property("Type");
        switch (type)
        {
            case "Car":
                return typeof(Car);
            case "Bike":
                return typeof(Bike);
        }

        throw new ApplicationException(String.Format(
            "The given vehicle type {0} is not supported!", type));
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...