Search code examples
c#httpjson.netasp.net-core-5.0

Response JObject values not completely filled in returned JSON


The response output from a JObject content is not well formed in an application.

Narrowing the problem to it's minimum possible size, there should be some missing detail that produce this behavior (very unlikely is other cause).

The following code shows a JSON payload to be the response from an API endpoint:

    [HttpPost]
    public async Task<ObjectResult> Post()
    {
      var json = JsonConvert.DeserializeObject<JObject>(
        @"{""parameter-1"":""J234546ZrVl"",""value-2"":""3E9CY3gertertmdALWMmHkvP"",""test-3"":""verify please""}");
      var result = new ObjectResult(json);

      return result;
    }

The response is received as:

  {"parameter-1":[],"value-2":[],"test-3":[]}

And should be:

  {"parameter-1":"J234546ZrVl","value-2":"3E9CY3gertertmdALWMmHkvP","test-3":"verify please"}

When debugging the variable json is correct, and has all the property values, but somehow it is not rendered correctly.

Any ideas?

  • This is using: ASP Net Core 5.0
  • ObjectResult is defined in: namespace Microsoft.AspNetCore.Mvc
  • Its constructor is: public ObjectResult(object value);
  • And has the interfaces:

public class ObjectResult : ActionResult, IStatusCodeActionResult, IActionResult


Solution

  • Thanks to dbc tips, we can use the legacy services, just serializing its return value with the previous Newtonsoft.Json library and deserializing with the new System.Text.Json.

    This method can do the trick and can be used across the whole application, probably for really big JSON values is not the optimum, but is clean and lean for our requirements.

    using Newtonsoft.Json;
    using Newtonsoft.Json.Linq;
    using System.Text.Json;
    
    ...
    
      public static JsonDocument JToken2JsonDocument(JToken input)
      {
        var jsonString = JsonConvert.SerializeObject(input);
        var json = JsonDocument.Parse(jsonString);
        return json;
      }
    

    The ObjectResult constructor can be called with the returned object and render correctly.