jQuery.parseJSON无法解析序列化的C#字典

时间:2012-05-31 13:07:13

标签: javascript jquery json serialization

我正在使用this tutorial来序列化C#字典。 C#字典被序列化为字符串。 @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ElementDivIDs))就像一个魅力。这是我得到的输出,:

  var jsonString = {"9":["ele9-tabs-attr9","ele9-tabs-attr48"],"10":["ele10-tabs-attr10"],"11":["ele11-tabs-attr11"],"12":["ele12-tabs-attr12","ele12-tabs-attr49"],"13":["ele13-tabs-attr13"],"14":["ele14-tabs-attr14"]}

我想将其转换为Javascript关联数组。 但是对 jquery.parseJSON 的调用返回NULL。

var dictionaryOfOtherDivs = jQuery.parseJSON( jsonString );

dictionaryOfOtherDivs在此之后为空。

这是我的代码:

<script type="text/javascript">
$(document).ready(function () {
     var jsonString = @Html.Raw(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ElementDivIDs))
     console.log(jsonString); 
     var dictionaryOfOtherDivs  = jQuery.parseJSON( jsonString ); 
     for(var dictKey in dictionaryOfOtherDivs)
     { 
        console.log("key = " + dictKey + ", value = " + dictionaryOfOtherDivs[dictKey]); 
     }
     //Do some more things
});
</script>

2 个答案:

答案 0 :(得分:6)

这不是JSON字符串;这是一个普通的对象文字。

您无需解析它。

答案 1 :(得分:2)

jQuery.parseJSON获取字符串并输出对象。但是,您决定将JSON本身注入到脚本中,因此JavaScript引擎已经将其解析为对象文字,就好像您已经将整个事情自己编写为常规代码一样。

简单地说,您已经有一个已解析的对象文字,您不再需要进行任何解析。