2015-04-25 69 views
0

我想從Java中的URL中獲取JSON並輸出結果。 這是我的json,來自www.thebluealliance.com/api/v2/match/2015arc_qm1。我想獲得match_number以及來自藍色和紅色聯盟的分數,並將其打印到我的控制檯。我正在使用GSON(Google JSON)。例如,我想這個代碼返回1,91,97 ...從URL協助JSON

{ 
    "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

發現嘗試了這一點,我沒有測試它,但從我在你的JSON文檔中看到的,你的代碼中有幾個問題,聯盟不是一個json數組,也是藍色和紅色不是json數組,它們是基於我在你的json文檔中看到的json對象,

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()); 
+0

只是要注意,我只是測試它,它工作正常。 – faljbour

+0

非常感謝! –