Allan Xu
Allan Xu

Reputation: 9298

The Json data in ASP.NET Core Web API response is being encoded

I have an ASP.NET Core 6 Web API controller. I am trying to return a mix of JSON strings along with plain C# objects as the result of one of controller's web methods. But I am facing a few problems.

The following web method can produce the problems I am facing:

[HttpGet("GetMixedJson")]
public IActionResult GetMixedJson()
{
    string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

    string json = JsonConvert.SerializeObject(Summaries, Formatting.Indented);

    JObject jsonObject = new JObject();
    jsonObject["thisFiledValueWillBeMissing"] = "JObject won't serialize :(";

    var resultObject = new
    {
        PlainCSharpFiled = "plain c# fields showing fine",
        jsonObject = jsonObject,
        TunneledJsonString = json
    };

    return new JsonResult(resultObject);
}

It produces the following JSON response:

{
  "plainCSharpFiled": "plain c# fields showing fine",
  "jsonObject": {
    "thisFiledValueWillBeMissing": []
  },
  "tunneledJsonString": "[\r\n  \u0022Freezing\u0022,\r\n  \u0022Bracing\u0022,\r\n  \u0022Chilly\u0022,\r\n  \u0022Cool\u0022,\r\n  \u0022Mild\u0022,\r\n  \u0022Warm\u0022,\r\n  \u0022Balmy\u0022,\r\n  \u0022Hot\u0022,\r\n  \u0022Sweltering\u0022,\r\n  \u0022Scorching\u0022\r\n]"
}

Problem #1: JObject jsonObject value is missing

Problem #2: The json data in TunneledJsonString is encoded, hence it is corrupted in the result, not usable.

Please note that I simplified the code. In my project, the actual objects data fields are coming from variety of sources and they are bigger. The more I save on memory cost the better.

What are my options to fix the problems #1 and #2?

Upvotes: 0

Views: 1332

Answers (1)

Ruikai Feng
Ruikai Feng

Reputation: 11611

in .net 6 web api projects,serialize and deserialize operations are based on System.Text.Json

You could add Newtonsoft JSON format support with this package:

Microsoft.AspNetCore.Mvc.NewtonsoftJson

and configure as below :

builder.Services.AddControllers().AddNewtonsoftJson();

The result:

enter image description here

object Summaries = new[]
            {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };

            

            string json = JsonConvert.SerializeObject(Summaries);

enter image description here

Upvotes: 1

Related Questions