我有一个泛型类,我想用它的一个属性值序列化它的子类。
为此,我编写了一个自定义的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": { ... } },
...
]
期望输出
[
{ ... },
{ ... },
{ ... },
...
]
最佳答案
首先,system.web.mvc.controller.json()不适用于json.net,它使用的JavaScriptSerializer 对json.net内容一无所知。如果您仍然想使用system.web.mvc.controller.json()调用,您应该执行类似this的操作。同时将WriteJson
更改为:
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
serializer.Serialize(writer, ((dynamic)value).attribute);
}
我认为这会让你的代码工作。