如何使用 JSON.NET 用十六进制编码的字符解析格式错误的 JSONP? [英] How to parse malformed JSONP with hex-encoded characters using JSON.NET?

查看:15
本文介绍了如何使用 JSON.NET 用十六进制编码的字符解析格式错误的 JSONP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I make a call to google's dictionary api like this:

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"));

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

However I get a response that this code fails to parse correctly:

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

解析在遇到这个时死亡:

The parse dies at encountering this:

"entries":[{"type":"example","terms":[{"type":"text","text":"x3cemx3ebarsx3c/emx3e of sunlight shafting through the broken windows","language":"en"}]}]}

x3cemx3ebarsx

x3cemx3ebarsx

东西会破坏解析

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

Is there some way to handle this JSONP response with JSON.NET?

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

The answer by aquinas to another "Parse JSONP" question shows nice regex x = Regex.Replace(x, @"^.+?(|)$", ""); to handle with JSONP part (may need to tweak regex for this case), so main part here is how to deal with hex-encoded characters.

推荐答案

参考:如何解码嵌入在 json 字符串中的 HTML 编码字符

字符串的 JSON 规范不允许十六进制 ASCII 转义序列,而只允许 Unicode 转义序列,这就是为什么无法识别转义序列的原因,这就是为什么使用 u0027 代替应该工作......现在你可以盲目地替换 x 和 u00 (这应该完全适用于有效的 JSON,虽然理论上有些注释可能会损坏,但谁在乎...:D)

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)

因此将您的代码更改为此将修复它:

So change your code to this will fix it:

        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);

这篇关于如何使用 JSON.NET 用十六进制编码的字符解析格式错误的 JSONP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆