gpt4 book ai didi

java - 访问多级 JSON 结构中的值

转载 作者:行者123 更新时间:2023-11-29 07:52:31 25 4
gpt4 key购买 nike

这是我的 JSON 结构:

{
"date":"19.11.2013",
"parent":{
"child1":[
{
"date":"2013-11-19",
"time":"10:30",
},
{
"date":"2013-11-19",
"time":"12:20",
}
],
"child2":[
{
"date":"2013-11-19",
"time":"10:30",
},
{
"date":"2013-11-19",
"time":"12:20",
}
]
}
}

这是我目前的代码:

public class json {
public static void main(String[] args) throws IOException, ParseException {

URL urlData = new URL("http://path.to/json");
BufferedReader reader = new BufferedReader(new InputStreamReader(
urlData.openConnection().getInputStream(), "utf-8"));
String struct = reader.readLine();

JSONParser parser = new JSONParser();
Object obj = parser.parse(struct);
JSONObject lev1 = (JSONObject) obj;
System.out.println(lev1.get("date"));
}
}

我有一个日期值(19.11.2013),但我不知道如何获取 child 的日期值和< em>时间。我正在使用 json-simple 库。

最佳答案

思路是这样的:

JSONObject parent = (JSONObject) lev1.get("parent");
JSONArray child1 = (JSONArray) parent.get("child1"); // same for child2
for (Object elem : child1) {
System.out.prinlnt("date = " + ((JSONObject) elem).get("date"));
System.out.prinlnt("time = " + ((JSONObject) elem).get("time"));
}

如果编译失败请告诉我,否则应该可以。

关于java - 访问多级 JSON 结构中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20080422/

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