c# - single - Escaping quotes in Newtonsoft JSON



remove double quotes from json string c# (1)

I've an object:

public class Test 
{
    public string Prop1 { get; set; }
}

I'd like to serialize it to json in a view, so in my cshtml:

<script type="text/javascript">
   var myJson = JSON.parse('@Html.Raw(JsonConvert.Serialize(Model.MyTest))');
</script>

It works, until Prop1 contains quotes, because it gets rendered as:

var myJson = JSON.parse('{"Prop1":"\"Quoted text\""}');

Unfortunately, such a line throws parse error. I know that it should be:

 var myJson = JSON.parse('{"Prop1":"\\"Quoted text\\""}');

How can I configure Newtonsoft to serialize it in a proper way?


You should not parse the string for a second time, since already serialized it as JSON, you can directly use it in Javascript (the JS in JSON).

var myJson = @Html.Raw(JsonConvert.Serialize(Model.MyTest));

Will output:

var myJson = {"Prop1":"\"Quoted text\""};

And, because you always need a JSFiddle to prove it works.





json.net