2

I am planning to do a JSON Response from an ASP.NET Core Controller but it is not as simple as I thought.

A simple string like {"ConfigValue":"192.168.1.125:1880"} should be serialized to a JsonObject and this object shall be part of the JSON Response.

But what the return Json(str) response is something like

{\u0022ConfigValue\u0022:\u0022192.168.1.125:1880\u0022}

I have no clue how to get rid of \u0022

public class commonController : Microsoft.AspNetCore.Mvc.Controller
{
    private  IConfiguration config;

    public commonController(IConfiguration configuration)
    {
        config = configuration;
    }
    // GET
    [Route("getConfigEntry/{key?}")]
    public JsonResult getConfigEntry(string? key)
    {
        Dictionary<string, string> dict = new Dictionary<string, string>
        {
            {"ConfigValue", "192.168.1.125:1880"}
        };
        str = JsonConvert.SerializeObject(dict,Formatting.None); //from debugger variable viewer {"ConfigValue":"192.168.1.125:1880"}
        return Json(str); // "{\u0022ConfigValue\u0022:\u0022192.168.1.125:1880\u0022}"
    }
}
1
  • 6
    Man, you gotta celebrate this day. You asked your first question and the greatest Jon Skeet answered it
    – Tugay
    Dec 22, 2020 at 23:21

1 Answer 1

9

You're serializing into JSON twice - first you're serializing the dictionary into a string, then you're serializing that string as a JSON value... which involves escaping quotes.

You should only serialize it once - you don't have to call JsonConvert.SerializeObject at all:

return Json(dict);
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.