Home > Mobile >  How can I convert these escape sequences back to their original characters?
How can I convert these escape sequences back to their original characters?

Time:05-19

JsonNode.Parse() seems to convert my < and > to the escape sequences \u003C and \u003E when they appear inside double-quotes "".

How can I convert these escape sequences back to their original characters?

This is my C# code:

using System.Text.Json.Nodes;
Console.WriteLine("JsonNode test");
var testString = "{ \"testString\" : \"<...>\" }";
Console.WriteLine($"{testString}, {testString.Length}");
var jsonNode = JsonNode.Parse(testString);
var jsonString = jsonNode.ToJsonString();
Console.WriteLine($"{jsonString}, {jsonString.Length}");

Output:

JsonNode test
{ "testString" : "<...>" }, 26
{"testString":"\u003C...\u003E"}, 32

I've tried the HtmlDecode and UrlDecode methods, but they are not right for this situation.

CodePudding user response:

The json is still valid, but I usually always recommend to use Neftonsoft.Json since it has much much less problems, but you can use a string Replace as well

var jsonNode = JsonNode.Parse(testString);
var jsonString = jsonNode.ToJsonString().Replace("\\u003C","<").Replace("\\u003E",">");

result

{"testString":"<...>"}

another option is to use UnsafeRelaxedJsonEscaping, but it is not safe in some cases

var options = new JsonSerializerOptions
    {
        Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping,
        WriteIndented = true
    };
var jsonString = System.Text.Json.JsonSerializer.Serialize(jsonNode, options);
  • Related