首页 > 解决方案 > 如何在 JSON.NET 中取消转义 unicode

问题描述

我有带有 Unicode 部分的 JSON,例如{ "val1": "\u003c=AA+ \u003e=AA-"} 如何将其转换为没有 Unicode 格式的 JSON? {"val1": "<=AA+ >=AA-"}

标签: c#unicodejson.net

解决方案


Json.NET 取消了 Unicode 序列的转义,因此您可以采用与如何使用 C# 在 .NET 中获取格式化 JSON 的答案JsonTextReader中使用的方法相同的方法?由Duncan Smart通过直接从 a 流式传输到 a using来重新格式化您的 JSON,而无需进行不必要的转义:JsonTextReaderJsonTextWriterJsonWriter.WriteToken(JsonReader)

public static partial class JsonExtensions
{
    // Adapted from this answer https://stackoverflow.com/a/30329731
    // To https://stackoverflow.com/q/2661063
    // By Duncan Smart https://stackoverflow.com/users/1278/duncan-smart

    public static string JsonPrettify(string json, Formatting formatting = Formatting.Indented)
    {
        using (var stringReader = new StringReader(json))
        using (var stringWriter = new StringWriter())
        {
            return JsonPrettify(stringReader, stringWriter, formatting).ToString();
        }
    }

    public static TextWriter JsonPrettify(TextReader textReader, TextWriter textWriter, Formatting formatting = Formatting.Indented)
    {
        // Let caller who allocated the the incoming readers and writers dispose them also
        // Disable date recognition since we're just reformatting
        using (var jsonReader = new JsonTextReader(textReader) { DateParseHandling = DateParseHandling.None, CloseInput = false })
        using (var jsonWriter = new JsonTextWriter(textWriter) { Formatting = formatting, CloseOutput = false })
        {
            jsonWriter.WriteToken(jsonReader);
        }
        return textWriter;
    }
}

使用这种方法,下面的代码:

var json = @"{ ""val1"": ""\u003c=AA+ \u003e=AA-""}";
var unescapedJson = JsonExtensions.JsonPrettify(json, Formatting.None);
Console.WriteLine("Unescaped JSON: {0}", unescapedJson);

输出

Unescaped JSON: {"val1":"<=AA+ >=AA-"}

演示小提琴在这里


推荐阅读