gpt4 book ai didi

java - 获取嵌套 JSONObject Java?

转载 作者:行者123 更新时间:2023-12-02 11:53:31 25 4
gpt4 key购买 nike

我正在尝试获取嵌套在另一个 JSON 对象中的 JSON 对象。当我运行主类时:

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

public class Main {
public static void main(String[] args) throws IOException, JSONException {
NBAPlayers players = new NBAPlayers();
JSONObject json = players.readJsonFromUrl("http://data.nba.net/10s/prod/v1/2017/players.json");
JSONObject League = json.getJSONObject("league");
JSONObject standard =League.getJSONObject("standard");
JSONObject firstName = standard.getJSONObject("firstName");
}
}

我收到错误:

 Exception in thread "main" org.json.JSONException: 

JSONObject["standard"] is not a JSONObject.

我正在使用 maven Artifact org.json:json 包。

最佳答案

这是示例中返回 url 的 json 的一部分

  {
"_internal": {
"pubDateTime": "2017-12-10 11:42:23.504",
"xslt": "xsl/league/roster/marty_active_players.xsl",
"eventName": "league_roster"
},
"league": {
"standard": [
{
"firstName": "Alex",
"lastName": "Abrines",
"personId": "203518",
"teamId": "1610612760",
"jersey": "8",
"isActive": true,
"pos": "G",
"heightFeet": "6",
"heightInches": "6",
"heightMeters": "1.98",
"weightPounds": "190",
"weightKilograms": "86.2",
"dateOfBirthUTC": "1993-08-01",
"teams": [
{
"teamId": "1610612760",
"seasonStart": "2016",
"seasonEnd": "2017"
}
],
"draft": {
"teamId": "1610612760",
"pickNum": "32",
"roundNum": "2",
"seasonYear": "2013"
},
"nbaDebutYear": "2016",
"yearsPro": "1",
"collegeName": "",
"lastAffiliation": "Spain/Spain",
"country": "Spain"
},
{
"firstName": "Quincy",
"lastName": "Acy",
"personId": "203112",
"teamId": "1610612751",
"jersey": "13",
"isActive": true,
"pos": "F",
"heightFeet": "6",
"heightInches": "7",
"heightMeters": "2.01",
"weightPounds": "240",
"weightKilograms": "108.9",
"dateOfBirthUTC": "1990-10-06",
"teams": [
{
"teamId": "1610612761",
"seasonStart": "2012",
"seasonEnd": "2013"
},
{
"teamId": "1610612758",
"seasonStart": "2013",
"seasonEnd": "2013"
},
{
"teamId": "1610612752",
"seasonStart": "2014",
"seasonEnd": "2014"
},
{
"teamId": "1610612758",
"seasonStart": "2015",
"seasonEnd": "2015"
},
{
"teamId": "1610612742",
"seasonStart": "2016",
"seasonEnd": "2016"
},
{
"teamId": "1610612751",
"seasonStart": "2016",
"seasonEnd": "2017"
}
],

如您所见,标准不是一个对象。它是数组。

您应该按如下方式更改代码

JSONArray standard =League.getJSONArray("standard");
for (int i = 0; i < standard.length(); i++) {
String firstName = standard.getJSONObject(i).getString("firstName");
}

关于java - 获取嵌套 JSONObject Java?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47740944/

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