2015-08-28 133 views
-1

我想在C#.NET 解析JSON字符串,但它抛出异常JSON字符串解析

string str= "{\"id\"=>\"\", \"textContent\"=>\"Services\", \"nodeName\"=>\"SPAN\", \"class\"=>\"ng-binding\", \"html\"=>\"<span class=\"ng-binding\">Services</span>\", \"rect\"=>{\"center_y\"=>252, \"center_x\"=>90, \"height\"=>26, \"width\"=>180, \"bottom\"=>108, \"left\"=>0, \"right\"=>90, \"y\"=>240, \"x\"=>0, \"top\"=>95}, \"nodeType\"=>\"ELEMENT_NODE\", \"webView\"=>\"NoResourceEntry-100\"}"; 
str = str.Replace("\"", "'"); 
str = str.Replace("=>", ":"); 
dynamic stuff = Json.Decode(str); 

string name = stuff.id; 
string address = stuff.textContent; 

它会给例外

型“System.TypeInitializationException”的第一次机会异常发生在JsonProject.exe中 'System.Web.Helpers.Json'的类型初始值设定项引发异常。

即使我不保换“与”仍然会抛出异常。

我还没有使用的Json以前和很新的JSON。我用葫芦,Android和那里我得到这个JSON字符串。

+0

您的json无效。 http://jsonlint.com/ – Eser

+0

你可以检查一下,如果json是否正确地得到“改造”,最终得到解码的str?通过json验证器运行它 – BobbyTables

回答

0

你将不得不与只是盲目地更换所有"'这里特别\"<span class=\"ng-binding\">Services</span>\",因为这将成为'<span class='ng-binding'>Services</span>'这是无效的问题。

我会建议使用重GEX到后=>或之前仅在更换"一个,

另外,作为在评论中提到使用调试器来找出str是什么,你要更换和使用在线工具来检查其有效

0

后你的字符串不是JSON。

试试这个:在你的字符串

string str= @" 
{""id"":"""", ""textContent"":""Services"", ""nodeName"":""SPAN"", ""class"":""ng-binding"", ""html"":""<span class='ng-binding'>Services</span>"", ""rect"":{""center_y"":252, ""center_x"":90, ""height"":26, ""width"":180, ""bottom"":108, ""left"":0, ""right"":90, ""y"":240, ""x"":0, ""top"":95}, ""nodeType"":""ELEMENT_NODE"", ""webView"":""NoResourceEntry-100""} 
"; 

str = str.Replace("=>", ":"); 
str.Dump(); 
dynamic stuff = Json.Decode(str); 

string name = stuff.id; 
string address = stuff.textContent; 
+0

它不工作。在http://jsonlint.com/如果我替换=>:它会显示有效的JSON,但在C#程序它抛出异常 – Shelar

0

做出改变为

<span class="ng-binding">Services</span> 

<span class='ng-binding'>Services</span> 

然后更换你的性格。

str = str.Replace("\"", ""); //with blank value 
str = str.Replace("=>", ":"); 

最后你的字符串变成这样了。

{"id":"", "textContent":"Services", "nodeName":"SPAN", "class":"ng-binding", "html":"<span class='ng-binding'>Services</span>", "rect":{"center_y":252, "center_x":90, "height":26, "width":180, "bottom":108, "left":0, "right":90, "y":240, "x":0, "top":95}, "nodeType":"ELEMENT_NODE", "webView":"NoResourceEntry-100"}