阅读JSON内容 [英] Reading JSON Content
问题描述
我使用jsoup来抓取一些HTML数据,并且效果很好。现在我需要拉一些JSON内容(只有JSON,而不是HTML)。我可以用jsoup轻松做到这一点,还是必须使用另一种方法做到这一点? jsoup执行的解析是对JSON数据进行编码,因此它不能与Gson正确解析。
I'm using jsoup to scrape some HTML data and it's working out great. Now I need to pull some JSON content (only JSON, not HTML). Can I do this easily with jsoup or do I have to do it using another method? The parsing that jsoup performs is encoding the JSON data so it's not parsing properly with Gson.
谢谢!
Thanks!
推荐答案
虽然很好,但 Jsoup 是一个HTML解析器,而不是JSON解析器,所以在这种情况下它是无用的。如果您尝试过,Jsoup会将返回的JSON隐式地放入< html>< head>
之类。你不想那样做。 Gson 是一款JSON解析器,所以您绝对需要它。
While great, Jsoup is a HTML parser, not a JSON parser, so it is useless in this context. If you ever attempt it, Jsoup will put the returned JSON implicitly in a <html><head>
and so on. You don't want to have that. Gson is a JSON parser, so you definitely need it.
您的具体问题很可能是您不知道如何向Gson提供返回JSON的URL。在这种情况下,您需要使用 URL#openStream()
来获取它的 InputStream
并使用 InputStreamReader
将它装饰成阅读器
,最终可以输入 Gson#fromJson()
,它接受 Reader
。
Your concrete problem is likely that you don't know how to feed an URL returning a JSON to Gson. In that case, you need to use URL#openStream()
to get an InputStream
of it and use InputStreamReader
to decorate it into a Reader
which finally can be fed to Gson#fromJson()
which accepts a Reader
.
InputStream input = new URL("http://example.com/foo.json").openStream();
Reader reader = new InputStreamReader(input, "UTF-8");
Data data = new Gson().fromJson(reader, Data.class);
// ...
这篇关于阅读JSON内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!