6

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

2 Answers 2

12

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.

Sign up to request clarification or add additional context in comments.

5 Comments

there are also many others special symbols like curly brackets... need some unified solution which supported by JSON.NET library
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.
A user enters then JSON manually. He can enter any symbol to message value.
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.
I agree with that, but user enters whole JSON.
2

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 Comments

everything is fine on client side. I need a server side solution.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.