【问题标题】:Asp.Net MVC returning a Json from a stringAsp.Net MVC 从字符串返回 Json
【发布时间】:2010-12-04 17:18:36
【问题描述】:

听起来很有趣,我将我的数据表数据转换成一个看起来像东西的字符串 像这样:

 { blocks: [
{"fromAge" : "60","fromAmount" : "0","toAge" : "64","toAmount" : "65000","color" : "red","orderNo" : "2"}, 
{"fromAge" : "66","fromAmount" : "0","toAge" : "72","toAmount" : "12000","color" : "red","orderNo" : "4"}, 
{"fromAge" : "64","fromAmount" : "0","toAge" : "72","toAmount" : "34400","color" : "red","orderNo" : "1"}, 
{"fromAge" : "64","fromAmount" : "19500","toAge" : "66","toAmount" : "50750","color" : "red","orderNo" : "3"}
]}

认为“块”类似于一个包含 4 个字典的数组,然后通过此操作将字符串返回到视图:

public ActionResult ChartDetails()
{       
       return Json(GetJson(datatable));
}

GetJson(DataTable dt) 是返回字符串的方法,在视图中我得到了这个:

"{ blocks: [{\"fromAge\" : \"60\",\"fromAmount\" : \"0\",\"toAge\" : \"64\",\"toAmount\" : \"65000\",\"color\" : \"Color [Orange]\",\"orderNo\" : \"2\"}, {\"fromAge\" : \"66\",\"fromAmount\" : \"0\",\"toAge\" : \"72\",\"toAmount\" : \"12000\",\"color\" : \"Color [Green]\",\"orderNo\" : \"4\"}, {\"fromAge\" : \"64\",\"fromAmount\" : \"0\",\"toAge\" : \"72\",\"toAmount\" : \"34400\",\"color\" : \"Color [Blue]\",\"orderNo\" : \"1\"}, {\"fromAge\" : \"64\",\"fromAmount\" : \"19500\",\"toAge\" : \"66\",\"toAmount\" : \"50750\",\"color\" : \"Color [Pink]\",\"orderNo\" : \"3\"}]}"

由于所有的 \" 和 "}" 和 " 我无法使用 JQuery 读取我的 Json,在我的情况下是否有某种方法可以返回具有正常编码的字符串?

【问题讨论】:

    标签: asp.net-mvc string json return


    【解决方案1】:

    您看到的字符串是 JSON,但已正确编码为 Javascript 字符串。您仍然需要在 Javascript 中将其解析为对象才能与 jQuery 一起使用。

    在此处查看来自 json.org 的“官方”JSON 解析器:https://github.com/douglascrockford/JSON-js 如果你的环境中有这个,你可以这样做:

    var jsonString = /* my string from the GetJson call */
    var data = JSON.parse(jsonString);
    

    然后您应该能够使用“数据”作为正确的地图列表。

    【讨论】:

    • 问题解决了!谢谢!我对 javascript 和 Json 真的很陌生......今天是漫长的一天搜索:)
    猜你喜欢
    • 1970-01-01
    • 2013-06-10
    • 2015-07-24
    • 1970-01-01
    • 2012-03-02
    • 1970-01-01
    • 2017-01-14
    • 1970-01-01
    • 2013-11-29
    相关资源
    最近更新 更多