Share via

null values in JSON values

net 6 newbie 121 Reputation points
2022-07-30T17:44:51.13+00:00

226309-jobject.jpg

When return type in Controller is JObject the values in the json object are displayed null.
But If I am trying to print on Console the out put is Ok.

How to deal with this?

Developer technologies | .NET | Other
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


2 answers

Sort by: Most helpful
  1. MylesF-0952 0 Reputation points
    2025-06-03T21:14:54.9466667+00:00

    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)

    Was this answer helpful?

    0 comments No comments

  2. Bruce (SqlWork.com) 84,071 Reputation points
    2022-07-31T17:43:39.713+00:00

    Most likely the server is returning an error. You don’t check the response code.

    Was this answer helpful?


Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.