Microsoft Technologies based on the .NET software framework. Miscellaneous topics that do not fit into specific categories.
I had a similar problem. It worked in the Console but not on the web page. Copilot couldn't solve it initially, but subsequently it gave me this answer.
- Serialization Issue: When you pass a JObject to Results.Ok(), ASP.NET Core uses its default JSON serializer (System.Text.Json) to serialize the object. However, JObject and JArray are part of Newtonsoft.Json, and the default serializer may not handle them properly.
My initial code was this:
JObject JSONMainObj = new JObject(
new JProperty("lastUpdated", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")),
new JProperty("version", "1.0.0")
);
foreach (var property in JSONMainObj.Properties())
{
if (property.Value.Type == JTokenType.String)
{
Console.WriteLine($"{property.Name}: {property.Value}");
}
}
return Results.Ok(JSONMainObj);
In the Console it returned this:
lastUpdated: 2025-06-03 21:58:36
version: 1.0.0
but on a web page it returned:
{"lastUpdated":[],"version":[]}
Copilot's suggestion was to:
- Force the use of Newtonsoft.Json for serialization by converting the JObject to a string before returning it.
It suggested changing the last line to:
return Results.Content(JSONMainObj.ToString(), "application/json");
The Console output was the same but the web page output was now correct:
{
"lastUpdated": "2025-06-03 22:07:54",
"version": "1.0.0"
}
(All thanks to Copilot, and I know the question is 3 years old)