Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 264
TrustworthySystems Avatar asked Oct 25 '25 11:10

TrustworthySystems


2 Answers

In my case, I had to replace to Newtonsoft.Json.

source: https://learn.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting

Relevant parts extracted from the link:

"To use the Newtonsoft.Json-based formatters, install the Microsoft.AspNetCore.Mvc.NewtonsoftJson NuGet package and configure it in Program.cs:"

    var builder = WebApplication.CreateBuilder(args);
    builder.Services.AddControllers()
        .AddNewtonsoftJson();

And change all my code to use JsonConvert.DeserializeObject().

like image 90
Cesar Avatar answered Oct 27 '25 02:10

Cesar


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.

like image 35
TrustworthySystems Avatar answered Oct 27 '25 02:10

TrustworthySystems



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!