0

I need to serialize some simple object from .NET to JavaScript...

But I've some problem with apex...

C# example

var obj = new { id = 0, label = @"some ""important"" text" };
string json1 = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
string json2 = Newtonsoft.Json.JsonConvert.SerializeObject(obj,
                   new Newtonsoft.Json.JsonSerializerSettings() 
                   {
                       StringEscapeHandling = Newtonsoft.Json.StringEscapeHandling.EscapeHtml 
                   });

JavaScript example

var resJson1= JSON.parse('{"id":0,"label":"some \"important\" text"}');
var resJson2= JSON.parse('{"id":0,"label":"some \u0022important\u0022 text"}');

Both parse give me the same error

VM517:1 Uncaught SyntaxError: Unexpected token I in JSON at position 23 at JSON.parse(<anonymous>)

Where am I wrong?

maccettura
  • 10,514
  • 3
  • 28
  • 35
giacomo
  • 51
  • 1
  • 10

1 Answers1

0

You're pasting the generated string of JSON into a JavaScript string constant without escaping it further. Try

console.log('{"id":0,"label":"some \"important\" text"}');

You'll see {"id":0,"label":"some "important" text"} i.e. the "important" quotes are no longer escaped by backslashes. (And you'll get the same for your \u0022 example too.) If you want to paste in the backslashes you'll have to escape them again:

var resJson1= JSON.parse('{"id":0,"label":"some \\"important\\" text"}');

The JSON you've generated with a single backslash would be fine if read from a file or URL, just not pasted into JavaScript as a string constant.

Rup
  • 33,765
  • 9
  • 83
  • 112
  • ok, now for develop i'm pasting it... there isn't a "c# way" to seriliaze in "pastable" javascript string? – giacomo Sep 12 '18 at 15:46