我有以下 JSON 文本。如何解析它以获取 pageName
、pagePic
、post_id
等值?
{
"pageInfo": {
"pageName": "abc",
"pagePic": "http://example.com/content.jpg"
},
"posts": [
{
"post_id": "123456789012_123456789012",
"actor_id": "1234567890",
"picOfPersonWhoPosted": "http://example.com/photo.jpg",
"nameOfPersonWhoPosted": "Jane Doe",
"message": "Sounds cool. Can't wait to see it!",
"likesCount": "2",
"comments": [],
"timeOfPost": "1234567890"
}
]
}
最佳答案
org.json库易于使用。
只需记住(在转换或使用诸如 getJSONObject
和 getJSONArray
之类的方法时)JSON 表示法
[ … ]
表示一个数组,因此库会将其解析为JSONArray
{ … }
表示一个对象,因此库会将其解析为JSONObject
示例代码如下:
import org.json.*;
String jsonString = ... ; //assign your JSON String here
JSONObject obj = new JSONObject(jsonString);
String pageName = obj.getJSONObject("pageInfo").getString("pageName");
JSONArray arr = obj.getJSONArray("posts"); // notice that `"posts": [...]`
for (int i = 0; i < arr.length(); i++)
{
String post_id = arr.getJSONObject(i).getString("post_id");
......
}
您可以从以下位置找到更多示例:Parse JSON in Java
关于java - 如何在Java中解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61055558/