Vibol
Vibol

Reputation: 785

Jsonconvert serializeobject not escaping single quote

C#, I have an Automobile class and in that class i have a vehicleTrim field. I use JsonConvert.SerializeObject to serialize that class and it is not escaping the single quote. This is causing an issue when i try to set the value of an object in the web via window.localStorage.setItem function.

example:

public class Automobile
{
    public string vehicleTrim { get; set; }
}

var test = new Automobile()
{
    vehicleTrim = "designer's package"
};

var serialized = JsonConvert.SerializeObject(test, Formatting.None);
// serialized output: {"vehicleTrim":"designer's package"}
// expected output :  {"vehicleTrim":"designer\'s package"}

so now i want to set this json object to the localstorage of my web by calling this

var jsSetScript = $"window.localStorage.setItem('automobile', '{serialized}');";
await Control.EvaluateJavascriptAsync(jsSetScript);

EvaluateJavascriptAsync returns this error trying to read the json SyntaxError: Unexpected identifier 's'. Expected ')' to end an argument list.

I manaully tried this with the escaped single quote and it was fine. So the question is how can i make serializedobject method escape the single quote?

Upvotes: 1

Views: 8175

Answers (1)

dbc
dbc

Reputation: 116721

"\'" is not even a valid JSON string literal. From the JSON spec:

JSON string specification

Thus ' does not need to be escaped, but if it is, it must appear as "\u0027". Only the 8 listed characters have a special, abbreviated escaping syntax. (For further details see RFC 8259.)

If "\u0027" meets your needs, then setting JsonSerializerSettings.StringEscapeHandling to StringEscapeHandling.EscapeHtml should do the trick. From the docs:

StringEscapeHandling Enumeration

Specifies how strings are escaped when writing JSON text.

Default           0   Only control characters (e.g. newline) are escaped.
EscapeNonAscii    1   All non-ASCII and control characters (e.g. newline) are escaped.
EscapeHtml        2   HTML (<, >, &, ', ") and control characters (e.g. newline) are escaped.

Thus the following now succeeds:

var settings = new JsonSerializerSettings
{
    StringEscapeHandling = StringEscapeHandling.EscapeHtml,
};
var serialized = JsonConvert.SerializeObject(test, Formatting.None, settings);

Console.WriteLine(serialized);
// Outputs {"vehicleTrim":"designer\u0027s package"}

Assert.IsTrue(!serialized.Contains('\'')); 
// Succeeds

Demo fiddle here.

Upvotes: 11

Related Questions