SpanJson icon indicating copy to clipboard operation
SpanJson copied to clipboard

JsonResult not serialized with SpanJson

Open silkfire opened this issue 6 years ago • 4 comments

I'm returning a JSON object in a controller action which I would like to use alternative property names for.

Unfortunately it doesn't seem like the [DataMember(Name="differentName")] is working. I'm getting the original property names instead. Am I missing something?

It works well when sending data with help of the FromBody attribute but not when outputting data it seems.

silkfire avatar Jan 04 '20 16:01 silkfire

I kinda figured it out. When I use return Json(object) in the controller action, it ignores the attributes. But when using return Ok(object) or return new ObjectResult(object) it works. The problem with this is that the server has to perform content negotiation in the latter case. Does Json(object) use System.Text.Json for some reason?

silkfire avatar Jan 04 '20 17:01 silkfire

Yes, JsonResult is not using the TextOutputFormatter, see https://github.com/aspnet/AspNetCore/blob/release/3.1/src/Mvc/Mvc.Core/src/Formatters/SystemTextJsonOutputFormatter.cs concept, but they use internally their own IActionExecuter implementation which then proceeds not to call the TextOutputFormatter but instead has it's own implementation again. https://github.com/aspnet/AspNetCore/blob/master/src/Mvc/Mvc.Core/src/Infrastructure/SystemTextJsonResultExecutor.cs

SpanJson does not provide an implementation for that type, if you want to use SpanJson, you should skip JsonResult.

I'll leave this open and change the title to missing Jsonresult support and flag it as enhancement.

Tornhoof avatar Jan 04 '20 17:01 Tornhoof

Thanks! I came to the very same conclusion just as I saw your reply :)

When using Newtonsoft, they simply override the default IActionResultExecutor<JsonResult> with their own implementation. Perhaps something similar can be done with SpanJson?

https://github.com/aspnet/AspNetCore/blob/5e953124e6071e10fd71834afc1e45d6e9a04b97/src/Mvc/Mvc.NewtonsoftJson/src/DependencyInjection/NewtonsoftJsonMvcCoreBuilderExtensions.cs#L84

https://github.com/aspnet/AspNetCore/blob/d5fd9fc2faeb079e05e3db31e29dcdea31841eec/src/Mvc/Mvc.NewtonsoftJson/src/NewtonsoftJsonResultExecutor.cs

silkfire avatar Jan 04 '20 18:01 silkfire

Yes, that's the idea. Unfortunately atleast ResponseContentTypeHelper, which is used in those executers is internal. Also JsonResult supports setting options at runtime and that probably won't be supported.

Tornhoof avatar Jan 04 '20 18:01 Tornhoof