DEH
DEH

Reputation: 1747

JSON string containing \" not being parsed

I am creating a JSON string using James Newton-King's excellent JSON libary. I create the JSON string using the following line of code:

string userJSON = Newtonsoft.Json.JsonConvert.SerializeObject(existingAdminUser, Newtonsoft.Json.Formatting.None);

The result looks as follows:

"{\"LoginId\":\"0f1b6c88-08ec-416f-b221-7568dc7c242a\",\"Firstname\":\"Charles\",\"Surname\":\"Barber\",\"Fullname\":\"Charles Barber\",\"Email\":\"[email protected]\",\"Systems\":null,\"IsValid\":false,\"IsValidExcludingSystems\":true,\"ValidationMessage\":\"\"}"

I am then placing this string into my http response using the following line of code:

HttpContext.Current.Response.Write("<input type=\"hidden\" name=\"adminextrainfo\" id=\"adminextrainfo\" value=\"" + userJSON + "\" />");

I am then trying to access/parse the JSON at the client, using:

var userdetails = $.parseJSON(valueOfHiddenField);

The parse attempt fails, and if I try viewing the contents of the field (using an alert) then I only see the very first { char. It seems that the \" character sequence is being treated as a newline by js. How can I encode the hidden field value at the server, or how can I deal with the hidden field value at the client such that it 'handles' the \" character sequence?

Thanks very much.

Upvotes: 0

Views: 1707

Answers (1)

Codo
Codo

Reputation: 78825

So we have a little escaping / encoding mess here. Your string:

"{\"LoginId\":\"0f1b6c88-08ec-416f-b221-7568dc7c242a\",\"Firstname\":\"Charles\",\"Surname\":\"Barber\",\"Fullname\":\"Charles Barber\",\"Email\":\"[email protected]\",\"Systems\":null,\"IsValid\":false,\"IsValidExcludingSystems\":true,\"ValidationMessage\":\"\"}"

isn't correct unless it is shown in some C# context (e.g. the Visual Studio debugger). All these slashes are only needed if you put this in C# source code. If you assign it to a variable, the variable will store it without the slashes as they are for escaping within the C# code only. They can't be the root of your problem because they only exist within the Visual Studio Debugger, not within your application.

However, you can't just insert the JSON into HTML. It contains several characters (e.g. the double quote at the second position), that have to be escaped because they have a special meaning in HTML.

So your fix should be:

HttpContext.Current.Response.Write("<input type=\"hidden\" name=\"adminextrainfo\" id=\"adminextrainfo\" value=\"" + Server.HtmlEncode(userJSON) + "\" />");

Upvotes: 1

Related Questions