使用Newtonsoft将包含转义字符的Json解析为JsonObject

时间:2016-05-14 08:25:01

标签: c# json json.net

我试图将json字符串解析为JsonObject但是我有异常(" Bad JSON转义序列:\ x.Path' original_query',第8行,位置35"。)

我知道我的JSON字符串中有不好的字符,但我无法转义这些字符。

这是我的工作:

String json =  File.ReadAllText("json.txt");

JObject json = JObject.Parse(json);

这是json文件数据:

{
"original_query" : "[currency == \x22USD\x22 \x26 ((exchange == \x22NASDAQ\x22) | (exchange == \x22NYSE\x22) | (exchange == \x22NYSEARCA\x22) | (exchange == \x22NYSEMKT\x22) | (exchange == \x22OTCBB\x22) | (exchange == \x22OTCMKTS\x22)) \x26 (forward_pe_1year \x3E= 0.00) \x26 (forward_pe_1year \x3C= 9.73)]",
"query_for_display" : "[currency == "USD" & ((exchange == "NASDAQ") | (exchange == "NYSE") | (exchange == "NYSEARCA") | (exchange == "NYSEMKT") | (exchange == "OTCBB") | (exchange == "OTCMKTS")) & (forward_pe_1year >= 0.00) & (forward_pe_1year <= 9.73)]"
}

我尝试替换这些字符:

//json = json.Replace("\x22", "\"");
//json = json.Replace("\x26", " ");
//json = json.Replace("\x3E", ">");
//json = json.Replace("\x3C", "<");

但它也给了我同样的例外。

1 个答案:

答案 0 :(得分:3)

您尝试替换失败,因为您使用的是C#字符串文字,其中\x是C#转义序列。你可以使用类似的东西:

json = json.Replace("\\x22", "\\\"");

...会在文本中用\x22替换\"

然而,看起来你收到的文本实际上包含了很多\x转义序列,所以我不是一个一个地替换它们,而是一次性完成。这是一个简短但完整的程序,可与您在聊天中提供的链接一起使用:

using System;
using System.IO;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string text = File.ReadAllText("f.txt");
        text = Regex.Replace(text, @"\\x[0-9a-fA-Z]{2}", ConvertHexEscape);
        JObject obj = JObject.Parse(text);
        Console.WriteLine(obj);
    }

    static string ConvertHexEscape(Match match)
    {
        string hex = match.Value.Substring(2);
        char c = (char) Convert.ToInt32(hex, 16);
        // Now we know the character we're trying to represent,
        // escape it if necessary.
        switch (c)
        {
            case '\\': return @"\\";
            case '"': return "\\\"";
            default: return c.ToString();
        }
    }
}