17

我正在尝试使用 Json.NET 和自定义 JsonConverter 对象反序列化一个类。该类当前使用 JsonConverterAttribute 定义了一个用于默认序列化的转换器。我需要通过传入自定义转换器来进行自定义反序列化。但是,反序列化似乎仍然使用默认转换器。如何让 Json.NET 更喜欢我的自定义转换器?

这是一些演示该问题的示例代码。我正在使用 NewtonSoft.Json 4.5.11:

void Main()
{
    JsonConvert.DeserializeObject<Foo>("{}"); // throws "in the default converter"
    var settings = new JsonSerializerSettings { Converters = new[] { new CustomConverter() } };
    JsonConvert.DeserializeObject<Foo>("{}", settings); // still throws "in the default converter" :-/
}

[JsonConverter(typeof(DefaultConverter))]
public class Foo {
}

public class DefaultConverter : JsonConverter {
    public override bool CanConvert(Type objectType)
    {
        return typeof(Foo).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new Exception("in the default converter!");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new Exception("in the default converter!");
    }
}

public class CustomConverter : JsonConverter {
    public override bool CanConvert(Type objectType)
    {
        return typeof(Foo).IsAssignableFrom(objectType);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        throw new Exception("in the custom converter!");
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        throw new Exception("in the custom converter!");
    }
}
4

1 回答 1

22

您需要使用自定义合同解析器。仅当未为类型指定转换器时,默认合同解析器才使用设置中的转换器。

class CustomContractResolver : DefaultContractResolver
{
    protected override JsonConverter ResolveContractConverter (Type objectType)
    {
        if (typeof(Foo).IsAssignableFrom(objectType))
            return null; // pretend converter is not specified
        return base.ResolveContractConverter(objectType);
    }
}

用法:

JsonConvert.DeserializeObject<Foo>("{}", new JsonSerializerSettings {
    ContractResolver = new CustomContractResolver(),
    Converters = new[] { new CustomConverter() },
});
于 2013-06-28T17:17:26.673 回答