Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core Json object is strange formatted with \u0022

Tags:

c#

json.net

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}"
    }
}
like image 772
D.S Avatar asked Jan 26 '26 00:01

D.S


1 Answers

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);
like image 156
Jon Skeet Avatar answered Jan 28 '26 14:01

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!