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



我试图将json字符串解析为JsonObject,但遇到异常("错误的json转义序列:\x.路径'original_query',第8行,位置35。")

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

这是我的作品:

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

这里是json文件数据:

{
"original_query" : "[currency == x22USDx22 x26 ((exchange == x22NASDAQx22) | (exchange == x22NYSEx22) | (exchange == x22NYSEARCAx22) | (exchange == x22NYSEMKTx22) | (exchange == x22OTCBBx22) | (exchange == x22OTCMKTSx22)) 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", "<");

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

您的替换尝试失败,因为您使用的是C#字符串文字,其中x是C#转义序列。您本可以使用以下内容:

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

其将用文本中的CCD_ 3替换CCD_。

然而,看起来你收到的文本实际上包含了很多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();
        }
    }
}

相关内容

  • 没有找到相关文章

最新更新