c# - ASP.NET Core Json 对象的格式很奇怪\u0022

标签 c# json.net

我打算从 ASP.NET Core Controller 执行 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}"
    }
}

最佳答案

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

您应该只将它序列化一次 - 您根本不必调用 JsonConvert.SerializeObject:

return Json(dict);

关于c# - ASP.NET Core Json 对象的格式很奇怪\u0022,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65416993/

相关文章:

c# - 如何重写 C# 中的 ToString() 方法?

c# - 根据背景使前景颜色为黑色或白色

c# - 使用超过 2^31 个元素的虚拟化集合进行 UI 虚拟化

c# - Newtonsoft Json反序列化: How to throw an error if/when the given json string has MORE properties than necessary?

c# - 列表中不同值的不同 JsonSerializerSettings

c# - 如何从泛型类型中获取 <T> 的名称并将其传递给 JsonProperty()?

c# - 为什么ConcurrentQueue提供TryPeek()和TryDequeue(),而Queue提供Peek()和Dequeue()?

c# - 具有多个不同提交按钮的 MVC Razor 表单?

c# - 具有自定义属性的字典的 Newtonsoft Json 序列化

c# - 将平面字典序列化为多子对象 JSON