gpt4 book ai didi

java - 如何在Java中解析JSON

转载 作者:太空宇宙 更新时间:2023-11-04 10:10:24 25 4
gpt4 key购买 nike

我有以下 JSON 文本。如何解析它以获取 pageNamepagePicpost_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库易于使用。

只需记住(在转换或使用诸如 getJSONObjectgetJSONArray 之类的方法时)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

可下载的jar:http://mvnrepository.com/artifact/org.json/json

关于java - 如何在Java中解析JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52429288/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com