JSON.Net deserialize string which contains special characters

21,383

Solution 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 });

Solution 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.

Share:
21,383
ohavryl
Author by

ohavryl

Updated on December 21, 2020

Comments

  • ohavryl
    ohavryl over 3 years

    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: {.

  • ohavryl
    ohavryl over 10 years
    everything is fine on client side. I need a server side solution.
  • Roman Pushkin
    Roman Pushkin over 10 years
    @ohavryl, actually you're trying to pass the broken json from the client side. So I think the best way is to fix the javascript.
  • ohavryl
    ohavryl over 10 years
    there are also many others special symbols like curly brackets... need some unified solution which supported by JSON.NET library
  • Brian Rogers
    Brian Rogers over 10 years
    If the JSON is created using a JSON serializer (like JsonConvert.SerializeObject() in Json.Net), then all the special characters will be escaped properly. Then the string will be able to be parsed.
  • ohavryl
    ohavryl over 10 years
    A user enters then JSON manually. He can enter any symbol to message value.
  • Brian Rogers
    Brian Rogers over 10 years
    The users enters the whole JSON, or just the message? If just the message, then you can put the message into an object and serialize it, and the serializer will take care of the escaping. If the user enters the whole JSON, then they are responsible for the escaping. You would need to validate that it is correct before accepting it. One way to do this is by attempting to deserialize the JSON inside of a try/catch. If you catch an exception then the JSON is invalid.
  • ohavryl
    ohavryl over 10 years
    I agree with that, but user enters whole JSON.