我正在尝试从Java中的URL获取JSON,并输出结果。 这是我的json,来自www.thebluealliance.com/api/v2/match/2015arc_qm1。我想获得match_number,以及来自蓝色和红色联盟的分数,并将其打印到我的控制台。我使用的是GSON(Google JSON)。例如,我希望此代码返回1,91,97 ...
{
"comp_level": "qm",
"match_number": 1,
"videos": [],
"time_string": null,
"set_number": 1,
"key": "2015arc_qm1",
"time": 1429795800,
"score_breakdown": {
"blue": {
"auto": 0,
"foul": 12
},
"red": {
"auto": 0,
"foul": 0
}
},
"alliances": {
"blue": {
"score": 91,
"teams": [
"frc1706",
"frc2907",
"frc2363"
]
},
"red": {
"score": 97,
"teams": [
"frc2914",
"frc360",
"frc207"
]
}
},
"event_key": "2015arc"
}
我的Java代码可以在下面找到
Gson gson = new Gson();
String sURL = "http://www.thebluealliance.com/api/v2/match/2015arc_qm
1?X-TBA-App-Id=frc1810:alex-webber:v01";
URL url = new URL(sURL);
HttpURLConnection request = (HttpURLConnection) url.openConnection();
request.connect();
JsonParser jp = new JsonParser();
JsonElement root = jp.parse(new InputStreamReader((InputStream) request
.getContent()));
JsonObject rootobj = root.getAsJsonObject();
JsonElement results = rootobj
.getAsJsonObject().get("match_number")
.getAsJsonObject().getAsJsonArray("alliances").get(4)
.getAsJsonObject().getAsJsonArray("blue").getAsJsonObject().get("score");
String match = results.getAsString();
答案 0 :(得分:0)
JsonObject rootobj = root.getAsJsonObject();
JsonElement match_number = rootobj.get("match_number");
JsonObject alliances = rootobj.getAsJsonObject("alliances");
JsonElement blue = alliances.getAsJsonObject("blue").get("score");
JsonElement red = alliances.getAsJsonObject("red").get("score");
System.out.println(match_number.getAsString()+","+blue.getAsString()+","+red.getAsString());