【问题标题】:Deserialize JSON in Dictionary in Web Api: always empty string在 Web Api 中的字典中反序列化 JSON:始终为空字符串
【发布时间】:2014-05-24 15:18:32
【问题描述】:

我有这样的 JSON 字符串:{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}

我想将它发送到 Web Api 控制器而不使用 ajax 请求进行更改:

$.ajax({ type: "POST", url: "Api/Serialize/Dict", data: JSON.stringify(sendedData), dataType: "json" });

在 Web Api 我有这样的方法:

[HttpPost]
public object Dict(Dictionary<int, List<int>> sendedData)
{
    var d1 = Request.Content.ReadAsStreamAsync().Result;
    var rawJson = new StreamReader(d1).ReadToEnd();
    sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);
    return null;
}

rawJson 始终是空字符串。我不明白为什么? 但d1.Length 与 JSON 字符串中的相同。我不知道如何从d1获取JSON字符串...

谢谢!

【问题讨论】:

  • 尝试使用[FromBody]属性public object Dict([FromBody] Dictionary&lt;int, List&lt;int&gt;&gt; sendedData)
  • 我试过了——同样的情况……
  • 用对象替换 sendedData 的类型,看看你确实得到了什么
  • 在执行ajax调用时使用内容类型参数而不是dataTypecontentType: "application/json; charset=utf-8"
  • 谢谢!我什至不知道,我是怎么错过的!它有效!

标签: c# ajax asp.net-mvc json asp.net-web-api


【解决方案1】:

执行ajax调用时使用内容类型参数而不是dataType:

$.ajax({ 
       type: "POST",
       url: "Api/Serialize/Dict", 
       contentType: "application/json; charset=utf-8", //!
       data: JSON.stringify(sendedData) 
});

【讨论】:

    猜你喜欢
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-24
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多