相关疑难解决方法(0)

Json.NET如何覆盖通过属性定义自定义JsonConverter的类型的序列化?

我试图使用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 …
Run Code Online (Sandbox Code Playgroud)

c# json.net

17
推荐指数
1
解决办法
2万
查看次数

标签 统计

c# ×1

json.net ×1