Json.NET custom JsonConverter is ignored

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"); // 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<,>); } } 

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

 [ { ... }, { ... }, { ... }, ... ] 
+5
source share
2 answers

First of all, System.Web.Mvc.Controller.Json () does not work with Json.NET - it uses a JavaScriptSerializer that does not work I do not know anything about your Json.NET materials. If you still want to use the System.Web.Mvc.Controller.Json () call, you should do something like this . Also change WriteJson to this:

 public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { serializer.Serialize(writer, ((dynamic)value).attribute); } 

I think this should make your code work.

+6
source

The documentation says: To apply a JsonConverter to collection items, use JsonArrayAttribute, JsonDictionaryAttribute, or JsonPropertyAttribute and set the ItemConverterType property to the type of converter you want to use.

http://james.newtonking.com/json/help/html/SerializationAttributes.htm

Maybe this will help.

+1
source

Source: https://habr.com/ru/post/1200401/


All Articles