我正在从远程JSON中提取数据,网址是http://hndroidapi.appspot.com/news/format/json/page/?appid=test。我遇到的问题是,这个API似乎没有正确处理UTF-8编码(如果我错了,请纠正我)。例如,目前传递的结果的一部分是 。
注意
编辑:
以下是我下载JSON的方式:
{
"title":"IPad - please don€™t ding while you and I are asleep ",
"url":"http://modern-products.tumblr.com/post/25384729998/ipad-please-dont-ding-while-you-and-i-are-asleep",
"score":"10 points",
"user":"roee",
"comments":"18 comments",
"time":"1 hour ago",
"item_id":"4128497",
"description":"10 points by roee 1 hour ago | 18 comments"
}
注意
don€™t
。它对此类字符不可行并不是唯一的例子。鉴于我无法控制API,有什么办法可以将数据转换为干净的东西吗?编辑:
以下是我下载JSON的方式:
hn_url = "http://hndroidapi.appspot.com/news/format/json/page/?appid=test"
url = URI.parse(hn_url)
# Attempt to get the json
req = Net::HTTP::Get.new(hn_url)
req.add_field('User-Agent', 'Test')
res = Net::HTTP.start(url.host, url.port) {|http| http.request(req) }
response = res.body
if response.nil?
puts "Bad response when fetching HN json"
return
end
# Attempt to parse the json
result = JSON.parse(response)
if result.nil?
puts "Error parsing HN json"
return
end
编辑2:
刚刚发现了API的GitHub页面,看起来这是一项未解决的问题。 我还不确定是否有任何解决方法可以从我的端口执行: https://github.com/glebpopov/Hacker-News-Droid-API/issues/4
Content-Type
标头设置为application/json; charset=utf-8
,这看起来是正确的。你是如何获取响应主体的?我建议尝试使用像Dev HTTP Client
或 CURL 这样的浏览器工具检查响应,看看你的应用程序得到的是否与实际响应有所不同。如果有差异,那么你的代码可能处理不正确。 - fdsaasputs res.body
在控制台中查看确切的响应。你是否通过result
对象看到了后面的奇怪符号? - fdsaas€™
,而不是撇号。这在 res.body 和稍后的 result 对象中都是如此。我认为这是因为 API 没有正确地表示撇号。所以,我希望能够以某种方式进行补偿。 - hodgesmr