JSON.Net deserialize string which contains special characters

限于喜欢 提交于 2019-12-10 10:23:11

问题


How do I parse JSON string with one of the values containing special characters?

JObject obj = JObject.Parse(str);

str value:

{
  "message": "some !@#$%^&*(){}:"?/?/|"':>;><{"d":"v"}"
}

I have got execption: After parsing a value an unexpected character was encountered: {.


回答1:


Take your JSON and .stringify() it.

{
  "message": JSON.stringify("your text here")
}

If you have raw data in your ASP.NET MVC view, you can follow this way:

{
  "message": JSON.stringify("@Html.Raw(HttpUtility.JavaScriptStringEncode(Model.MyString))")
}

You can also try more preferred way:

JSON.stringify({ "message" : message });



回答2:


That JSON is invalid. If a JSON string contains special characters like double quotes ", backslashes \ or slashes /, they need to be escaped with backslashes \. (See JSON.org.) No JSON parser, including Json.Net, will be able to deal with a JSON string that isn't properly formatted in the first place.

Your JSON would need to look like this to be able to be parsed correctly:

{
  "message": "some !@#$%^&*(){}:\"?/?/|\"':>;><{\"d\":\"v\"}"
}

The solution is to correctly serialize the string at the source.



来源:https://stackoverflow.com/questions/20706943/json-net-deserialize-string-which-contains-special-characters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!