ASP.NET Core Json 对象的格式很奇怪,带有 \u0022

问题描述 投票:0回答:2

我计划从 ASP.NET Core 控制器执行 JSON 响应,但它并不像我想象的那么简单。

{"ConfigValue":"192.168.1.125:1880"}
这样的简单字符串应该序列化为 JsonObject,并且该对象应成为 JSON 响应的一部分。

但是返回 Json(str) 响应是什么样的

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

我不知道如何摆脱\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}"
    }
}
c# json.net
2个回答
11
投票

您将序列化为 JSON 两次 - 首先将字典序列化为字符串,然后将该字符串序列化为 JSON 值...这涉及转义引号。

您应该只序列化一次 - 您根本不必调用

JsonConvert.SerializeObject

return Json(dict);

0
投票

当我使用以下格式创建 jsonstring 时遇到此错误,其中键和值用双引号括起来

@"{
        ""product"": {
            ""x"": ""123456"",
            ""y"": 0
        }

然后我通过使用内置函数创建 json 实例来解决这个问题,该实例可以通过包裹在

HttpResponseMessage
中的电线发送,其中 jsonBody 是一个 POCO 模型/类

JsonContent.Create(jsonBody, options: new JsonSerializerOptions { DictionaryKeyPolicy = JsonNamingPolicy.CamelCase })
© www.soinside.com 2019 - 2024. All rights reserved.