开发者

How can I escape my user generated text with Json.NET in ASP.NET 2.0

开发者 https://www.devze.com 2023-03-16 07:25 出处:网络
I have an aspx page that retrieves some user generated text from the database and passes to JQuery Ajax method as a JSON Object.

I have an aspx page that retrieves some user generated text from the database and passes to JQuery Ajax method as a JSON Object.

The JSON string it self is simple {"popContent开发者_如何学运维":"<div>html content</div>"}.

The content may have elements such as single quotes, double quotes, carriage returns etc. The problem is as I'm using .net framework 2.0, struggling to find a method that would escape these elements.

I have tried to use Json.NET to escape this. The documentation refers to serializing objects, but not clear on how to escape a string. Is this possible with Json.NET? Or should I create an object with this string and serialize that?

Thanks


It is possible using JSON.NET.

Since you're using .Net 2.0, you don't have anonymous types and cannot do this:

var result = new {
  popContent = "<div>html content</div>"
};

So I suggest you create a class that has the appropriate properties, then set the HTML content on the property and use JSON.NET for serialize the entire object.

Something like this:

ContentWrapper cw = new ContentWrapper();
cw.PopContent = "<div>html content</div>";
string json = JsonConvert.SerializeObject(cw);
0

精彩评论

暂无评论...
验证码 换一张
取 消