1

Hi I Have the need to escape a json string and I think using Newtonsoft.Json does the trick however

var unescapedString=System.Text.Json.JsonSerializer.Serialize(MyObject);
var escapedJsonString = JsonConvert.ToString(unescapedString);//Newtonsoft.Json

How can I do the same (escape a json string) using System.Text.Json?

dbc
  • 104,963
  • 20
  • 228
  • 340
developer9969
  • 4,628
  • 6
  • 40
  • 88
  • Hi not sure why this has been closed the link provided does not offer a solution that works – developer9969 Oct 23 '21 at 06:52
  • 1
    `JsonConvert.ToString()` serializes the string as a JSON string primitive, so you are actually just double-serializing your `MyObject`. Thus in System.Text.Json you can do `var escapedJsonString = System.Text.Json.JsonSerializer.Serialize(unescapedString);`. Does that answer your question? – dbc Nov 01 '21 at 16:59
  • Yes it does all clear now – developer9969 Nov 02 '21 at 17:24
  • My guess was `JsonValue.Create(unescapedString)?.ToJsonString()` but `JsonSerializer.Serialize(unescapedString)` looks better. – SerG Apr 05 '23 at 22:53

0 Answers0