Asp.Net Web Api& JSON.Net - 将主体反序列化为.Net通用对象

时间:2013-02-20 10:13:43

标签: json list dictionary asp.net-web-api

我想将正文反序列化为.net类(字典和列表)。

(所以我的代码对于xml和json是透明的)

public HttpResponseMessage Post([FromBody]IDictionary<string, object> body)
        {
        }

目前我使用转换器来处理嵌套字典反序列化。

class IDictionaryConverter : CustomCreationConverter<IDictionary<string, object>>
{
    public override IDictionary<string, object> Create(Type objectType)
    {
        return new Dictionary<string, object>();
    }

    public override bool CanConvert(Type objectType)
    {
        // in addition to handling IDictionary<string, object>
        // we want to handle the deserialization of dict value
        // which is of type object
        return objectType == typeof(object) || base.CanConvert(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null)
            return base.ReadJson(reader, objectType, existingValue, serializer);

        // if the next token is not an object
        // then fall back on standard deserializer (strings, numbers etc.)
        return serializer.Deserialize(reader);
    }
}

但是嵌套的JLists不会转换为List。 也许我可以创建一个IListConverter,但是有更好的方法吗?

我想在我的web api中只有一个代码。不是:如果json这样做,如果xml这样做......

1 个答案:

答案 0 :(得分:1)

这解决了我的问题:

class IDictionaryConverter : CustomCreationConverter<IDictionary<string, object>>
    {
        public override IDictionary<string, object> Create(Type objectType)
        {
            return new Dictionary<string, object>();
        }

        public override bool CanConvert(Type objectType)
        {
            // in addition to handling IDictionary<string, object>
            // we want to handle the deserialization of dict value
            // which is of type object
            return objectType == typeof(object) || base.CanConvert(objectType);
        }

        public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
        {
            if (reader.TokenType == JsonToken.StartObject || reader.TokenType == JsonToken.Null)
                return base.ReadJson(reader, objectType, existingValue, serializer);

            if (reader.TokenType == JsonToken.StartArray)
                return serializer.Deserialize<IList<object>>(reader);

            // if the next token is not an object
            // then fall back on standard deserializer (strings, numbers etc.)
            return serializer.Deserialize(reader);
        }
    }