使用java提取JSON字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22074192/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extracting JSON fields using java
提问by lulu
I am trying to extract a person's details who liked a facebook page by passing the page id as parameter. I extracted the JSON content of that page and now from that I want to extract name and id of users.
我试图通过将页面 id 作为参数传递来提取喜欢 facebook 页面的人的详细信息。我提取了该页面的 JSON 内容,现在我想从中提取用户的名称和 ID。
How do I achieve that ?
我如何做到这一点?
Code:
代码:
JSONObject json = readurl("https://graph.facebook.com/pageid");
System.out.println(json.toString());
System.out.println("Page id is:"+json.get("id"));
JSON:
JSON:
"likes":{
"data":[
{
"id":"*******",
"name":"vv"
},
{
"id":"********",
"name":"abc"
},
采纳答案by Pradeep Simha
Code like this would do the trick.
像这样的代码可以解决问题。
JSONObject json = readurl("https://graph.facebook.com/pageid");
JSONArray dataJsonArray = json.getJSONArray("data");
for(int i=0; i<dataJsonArray.length; i++) {
JSONObject dataObj = dataJsonArray.get(i);
String id = dataObj.getString("id");
//Similarly you can extract for other fields.
}
Basically data
is a JSONArray since it starts with [
. So simply get
would not work, you must use JSONArray.
基本上data
是一个 JSONArray,因为它以[
. 所以根本get
行不通,你必须使用 JSONArray。
Note:I haven't compiled this code, but I think I gave you idea to proceed. Also refer thislink to get hold of basics of parsing JSON in java.
注意:我还没有编译这段代码,但我想我给了你继续的想法。另请参阅此链接以了解在 Java 中解析 JSON 的基础知识。
回答by Thom
I use google's Gson library from: https://code.google.com/p/google-gson/
我使用谷歌的 Gson 库:https: //code.google.com/p/google-gson/
回答by trylimits
This snippet is not tested, but I'm pretty sure it works:
此代码段未经测试,但我很确定它有效:
JSONArray data = json.getJSONArray("data");
for (int i=0; i < data.length(); i++) {
JSONObject o = data.getJSONObject(i);
sysout(o.getString("id");
sysout(o.getString("name");
}