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?
namespace Microsoft.AspNetCore.Mvcpublic ObjectResult(object value);public class ObjectResult : ActionResult, IStatusCodeActionResult, IActionResult
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().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With