Tôi đang cố gắng deserialize một lớp bằng cách sử dụng Json.NET và một đối tượng JsonConverter tùy chỉnh. Lớp hiện định nghĩa một trình biến đổi để tuần tự hóa mặc định bằng cách sử dụng JsonConverterAttribute. Tôi cần phải làm một deserialization tùy chỉnh bằng cách đi qua trong một công cụ chuyển đổi tùy chỉnh. Tuy nhiên, việc deserialization vẫn có vẻ là sử dụng công cụ chuyển đổi mặc định. Làm thế nào tôi có thể nhận được Json.NET để thích chuyển đổi tùy chỉnh của tôi?Json.NET làm thế nào để ghi đè lên tuần tự hóa cho một loại định nghĩa một JsonConverter tùy chỉnh thông qua một thuộc tính?
Dưới đây là một chút mã mẫu thể hiện sự cố. Tôi đang sử dụng 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!");
}
}