【发布时间】:2014-10-09 02:24:19
【问题描述】:
我有一个泛型类,我想用它的一个属性的值序列化它的子类。
为此,我编写了一个自定义 JsonConverter 并将其附加到具有 JsonConverter(Type) 属性的基类 - 但是,它似乎从未被调用过。作为参考,如下例所示,我正在使用System.Web.Mvc.Controller.Json()方法序列化对象的List<>。
如果有更好的方法来达到相同的结果,我绝对愿意接受建议。
示例
查看功能
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": { ... } },
...
]
期望的输出
[
{ ... },
{ ... },
{ ... },
...
]
【问题讨论】:
标签: c# asp.net-mvc json json.net