2

I'm trying to deserialize a JSON object in c#, my problem is that one of the fields can contain html text (I plan on sanitizing it afterwards).

I’m using a JavaScriptSerializer object to deserialize, but I’m getting a “Invalid object passed in“ error (from the JavaScriptSerializer). If I pass plain text for that same field it works fine and the other fields (including a date and an array) in the object also deserialize correctly so it seems like the html is what’s tripping it up.

I’m using JSON.stringify to serialize the Javascript object and I’m passing it to my page via jQuery.

Is there something I’m supposed to do to in order to pass a string that contains html? I’ve tried enclosing it in quotes, but it didn’t help.

As an example of a string that's accepted vs what throws an error: "Test" is fine while

"<div style="text-align: center;">Test</div>" is not. Strangely <span> tags also seem to be fine.

2
  • Can you stringify the html strings before bundling them into one JSON object to pass back? Commented Jul 15, 2011 at 15:53
  • I tried, it made no difference. Commented Jul 15, 2011 at 16:06

4 Answers 4

2

Can you encode the html with the javascript escape() function before serializing.

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

Comments

2

You may have to encodeURIComponent in javascript, then HttpServerUtility.UrlDecode in .NET

Comments

0

You can't pass in HTML characters that aren't encoded for security reasons. You can override this in MVC.Net at the application of function level if you feel secure in your source.

1 Comment

I'm actually using webforms, but I'm guessing the the security issues should be the same. Escaping it like Barry said seems to have done the trick though. I understand that I'll need to sanitize the results afterwards though.
0

just do some replace like this jsonString.Replace(@"=""\""",@"=\""\""").Replace(@"\""""",@"\""\""").Replace(@"=""""", @"=\""\""")

1 Comment

While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.

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.