Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Serializing strings containing apostrophes with JSON.Net

Tags:

I am using JSON.Net as my serializer for a large MVC 3 web application in c# and the Razor view engine. For the initial page load in one view, there is a large amount of JSON dumped inside a script tag using @Html.Raw(JsonConvert.SerializeObject(myObject)).

The problem is that some values of some objects contain apostrophes (think names like O'Brien), which JSON.Net is not escaping or encoding in any way.

It's not an option to pre-encode the values stored in the database because that vastly complicates various other processes.

Is there a way to force JSON.Net to HTML encode the values of the objects that it serializes, the same way that the built-in JavaScriptSerializer does when you call JavaScriptSerializer.Serialize(myObject)? Or, is there a way to deal with this in the view?

like image 989
dodexahedron Avatar asked Aug 20 '12 17:08

dodexahedron


People also ask

What is serializing in JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object).

What is serializing and deserializing JSON in C#?

Serialization is the process of converting . NET objects such as strings into a JSON format and deserialization is the process of converting JSON data into . NET objects.

Is JSON serialize format?

JSON is a ubiquitous human-readable data serialization format that is supported by almost every popular programming language. JSON's data structures closely represent common objects in many languages, e.g. a Python dict can be represented by a JSON object , and a Python list by a JSON array .

Does JSON serialize data?

Json namespace provides functionality for serializing to and deserializing from JavaScript Object Notation (JSON). Serialization is the process of converting the state of an object, that is, the values of its properties, into a form that can be stored or transmitted.


1 Answers

JsonSerializerSettings settings = new JsonSerializerSettings {     StringEscapeHandling = StringEscapeHandling.EscapeHtml };  JsonConvert.SerializeObject(obj, settings); 
like image 182
rrymar Avatar answered Sep 17 '22 08:09

rrymar