【问题标题】:ASP.net - Returning an invalid json on client when serializing a dictionary [duplicate]ASP.net - 序列化字典时在客户端返回无效的 json [重复]
【发布时间】:2019-12-18 22:08:35
【问题描述】:

这个问题与模组提出的问题不同。因为我在这里返回一个字符串而不是一个对象。

我正在尝试将 json 字符串发送回客户端。但是它是无效的(格式不正确)关于如何解决这个问题的任何建议?

这是服务器端

    [HttpGet]
    public string foo()
    {
        Dictionary<string, string> response = new Dictionary<string, string>();
        response["itemID"] = "ABC";
        return JsonConvert.SerializeObject(response);
    }

在客户端我正在这样做

    using (WebClient client = new WebClient())
    {
       string clientResponse = client.DownloadString(url);
       Dictionary<string, string> response = JsonConvert.DeserializeObject<Dictionary<string, string>>(clientResponse);

    }

clientRepsonse 显然没有像这样正确格式化 json(如下所示)。这就是为什么它不能被反序列化

"{\"itemID\":\"ABC\"}"

关于如何解决此问题的任何建议。 在视觉工作室的当地人中,它看起来像这样"\"{\\\"itemID\\\":\\\"ABC\\\"}\"" 在预览中它看起来像这样 "{\"itemID\":\"ABC\"}"

【问题讨论】:

  • 转义字符是否包含在 json 字符串中,还是 Visual Studio 显示的方式? "{\"itemID\":\"ABC\"}" 作为字符串反序列化为 Dictionary&lt;string,string&gt; 就我所知。
  • 让我发布 Visual Studio 展示的内容
  • 您遇到什么错误?或者您只是查看了转义的字符串?我试过这个var dc=JsonConvert.DeserializeObject&lt;Dictionary&lt;string,string&gt;&gt;("{\"One\":\"A\",\"Two\":\"B\",\"Three\":\"C\"}");,效果很好。
  • 我将发布我看到的确切结果,我现在正在运行它
  • @JonathonChase 这就是它在视觉工作室中出现"{\"itemID\":\"ABC\"}" 的方式。当我尝试将其脱轨到字典时,它失败了。我不确定它为什么会失败。字符串对我来说看起来不错。但在当地人看来是这样的"\"{\\\"itemID\\\":\\\"ABC\\\"}\""

标签: c# asp.net json serialization


【解决方案1】:

尝试将 [Produces("application/json")] 添加到您的控制器级别。

[Produces("application/json")]
public class MyController : ControllerBase

【讨论】:

    猜你喜欢
    • 2021-02-18
    • 2019-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多