我有一个泛型类,我想用它的一个属性的值序列化它的子类。
为此,我写了一个自定义JsonConverter
并使用 JsonConverter(Type)
将其附加到基类属性 - 但是,它似乎从未被调用过。作为引用,如下例所示,我正在序列化一个 List<>
使用 System.Web.Mvc.Controller.Json()
的对象方法。
如果有实现相同结果的完全更好的方法,我绝对愿意接受建议。
示例
查看函数
public JsonResult SomeView()
{
List<Foo> foos = GetAListOfFoos();
return Json(foos);
}
自定义 JsonConverter
class FooConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
System.Diagnostics.Debug.WriteLine("This never seems to be run");
// This probably won't work - I have been unable to test it due to mentioned issues.
serializer.Serialize(writer, (value as FooBase<dynamic, dynamic>).attribute);
}
public override void ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
System.Diagnostics.Debug.WriteLine("This never seems to be run either");
return objectType.IsGenericType
&& objectType.GetGenericTypeDefinition() == typeof(FooBase<,>);
}
}
Foo 基类
[JsonConverter(typeof(FooConverter))]
public abstract class FooBase<TBar, TBaz>
where TBar : class
where TBaz : class
{
public TBar attribute;
}
Foo 实现
public class Foo : FooBase<Bar, Baz>
{
// ...
}
当前输出
[
{"attribute": { ... } },
{"attribute": { ... } },
{"attribute": { ... } },
...
]
期望的输出
[
{ ... },
{ ... },
{ ... },
...
]
最佳答案
发生在我身上的是,我按照 Visual Studio 的建议自动添加了 using
语句。并错误地添加了 using System.Text.Json.Serialization;
而不是 using Newtonsoft.Json;
所以我在目标类上使用了 System.Text.Json.Serialization.JsonConverterAttribute
。 Json.Net(正确地)忽略了它。
关于c# - Json.NET 自定义 JsonConverter 被忽略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25324912/