I have a general class whose children I want to serialize with the value of only one of its attributes.
For this purpose, I wrote a custom JsonConverter and bound it to a base class with the JsonConverter(Type) attribute, however it is never called. For reference, as shown in the following example, I serialize the List<> object using the System.Web.Mvc.Controller.Json() method.
If there is a better way to achieve the same result, I am absolutely ready for suggestions.
Example
View function
public JsonResult SomeView() { List<Foo> foos = GetAListOfFoos(); return Json(foos); }
Custom JsonConverter
class FooConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { System.Diagnostics.Debug.WriteLine("This never seems to be run");
base class foo
[JsonConverter(typeof(FooConverter))] public abstract class FooBase<TBar, TBaz> where TBar : class where TBaz : class { public TBar attribute; }
Foo implementation
public class Foo : FooBase<Bar, Baz> {
Current output
[ {"attribute": { ... } }, {"attribute": { ... } }, {"attribute": { ... } }, ... ]
Desired Conclusion
[ { ... }, { ... }, { ... }, ... ]
source share