gpt4 book ai didi

c# - 如何使用 JSON.NET 解析带有十六进制编码字符的格式错误的 JSONP?

转载 作者:行者123 更新时间:2023-11-30 13:39:20 25 4
gpt4 key购买 nike

我像这样调用 google 的字典 api:

var json = new WebClient().DownloadString(string.Format(@"http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q={0}&sl=en&tl=en", "bar"));

但是我得到的响应是此代码无法正确解析:

json = json.Replace("dict_api.callbacks.id100(", "").Replace(",200,null)", "");
JObject o = JObject.Parse(json);

解析在遇到这个时死了:

"entries":[{"type":"example","terms":[{"type":"text","text":"\x3cem\x3ebars\x3c/em\x3e of sunlight shafting through the broken windows","language":"en"}]}]}

\x3cem\x3ebars\x

东西杀死了解析

有没有办法用 JSON.NET 处理这个 JSONP 响应?

answer通过 aquinas另一个“解析 JSONP”问题显示了很好的正则表达式 x = Regex.Replace(x, @"^.+?\(|\)$", ""); 处理 JSONP 部分(可能需要为这种情况调整正则表达式),所以这里的主要部分是如何处理十六进制编码的字符。

最佳答案

引用:How to decode HTML encoded character embedded in a json string

JSON specs for strings do not allow hexadecimal ASCII escape-sequences, but only Unicode escape-sequences, which is why the escape sequence is unrecognized and which is why using \u0027 instead should work ... now you could blindly replace \x with \u00 (this should perfectly work on valid JSON, although some comments may get damaged in theory, but who cares ... :D)

因此将您的代码更改为这样可以修复它:

        var json = new WebClient().DownloadString(string.Format(@"http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q={0}&sl=en&tl=en", "bar"));

json = json
.Replace("dict_api.callbacks.id100(", "")
.Replace(",200,null)", "")
.Replace("\\x","\\u00");

JObject o = JObject.Parse(json);

关于c# - 如何使用 JSON.NET 解析带有十六进制编码字符的格式错误的 JSONP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12362456/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com