ASP.NET MVC - JSON.NET在我的鍵和值周圍添加了轉義引號

[英]ASP.NET MVC - JSON.NET adds escaped quotes around my keys and values

I have an MVC ApiController class in which I am trying to return JSON.

我有一個MVC ApiController類,我試圖返回JSON。

I am using Newtonsoft's JSON.NET serializer in the method:


// GET api/packages/5
public string Get(int id)
    var Packages = new Dictionary<string, string>();
    Packages.Add("Package 1", "One");
    Packages.Add("Package 2", "Two");
    Packages.Add("Package 3", "Three");
    Packages.Add("Package 4", "Four");

    return JsonConvert.SerializeObject(Packages);

But when viewed in my browser, I see the response:


"{\"Package 1\":\"One\",\"Package 2\":\"Two\",\"Package 3\":\"Three\",\"Package 4\":\"Four\"}"

with all the quotes escaped. This is obviously not readable by my client. Can anyone see where I am going wrong here? The content-type is returned as application/json (which is shown in Chrome developer tools also).

所有引號都逃脫了。這顯然是我的客戶無法讀取的。誰能看到我在哪里錯了? content-type作為application / json返回(也在Chrome開發人員工具中顯示)。

1 个解决方案



There is a simple method without using JSON.NET.


 public Dictionary<string, string> Get()
        var packages = new Dictionary<string, string>
                               {"Package 1", "One"},
                               {"Package 2", "Two"},
                               {"Package 3", "Three"},
                               {"Package 4", "Four"}

        return packages;

The result in IE is


{"Package 1":"One","Package 2":"Two","Package 3":"Three","Package 4":"Four"} 



粤ICP备14056181号  © 2014-2021