代码之家  ›  专栏  ›  技术社区  ›  Anand

如何在JSON.NET中取消对unicode的浏览

  •  1
  • Anand  · 技术社区  · 5 年前

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

    2 回复  |  直到 5 年前
        1
  •  0
  •   dbc    5 年前

    JsonTextReader ,因此您可以采用与中使用的方法相同的方法 this answer How do I get formatted JSON in .NET using C#? 通过 Duncan Smart 通过直接从 JsonTextReader JsonTextWriter 使用 JsonWriter.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-"}
    

    演示小提琴 here

        2
  •  -1
  •   Anand    5 年前

    我在Linqpad尝试了以下方法,效果很好。

    var s = @"{ ""val1"": ""\u003c=AA+ \u003e=AA-""}";
    System.Text.RegularExpressions.Regex.Unescape(s).Dump();