2017-12-02 264 views
0

我有這樣的代碼:訪問JSON數組(JAVA)的2維

String sURL = "https://example.com/json"; //just a string 
// Connect to the URL using java's native library 
URL url = new URL(sURL); 
HttpURLConnection request = (HttpURLConnection) url.openConnection(); 
request.connect(); 

// Convert to a JSON object to print data 
JsonParser jp = new JsonParser(); //from gson 
JsonElement root = jp.parse(new InputStreamReader((InputStream) request.getContent())); //Convert the input stream to a json element 
JsonObject rootobj = root.getAsJsonObject(); //May be an array, may be an object. 
String names = rootobj.get("names").getAsString(); 
System.out.println(names); 

我如何可以訪問該陣列的第二級在倒數第二行? 「名稱」是第一個工作正常的維度。
在PHP中的解決方案將是

$var = json[...][...] //for accessing the second dimension. 

這是如何在Java中做了什麼?像rootobj.get(「名稱/姓氏」)不起作用。

+1

你能告訴什麼樣的JSON看起來像 – bhspencer

+0

當然一個例子!像這樣一個這裏:https://api.github.com/users/mralexgray/repos 在第一行它說「0」 - >「ID」 我如何訪問ID? –

+0

刪除'getAsString()',並將這些名稱當作一個新對象 –

回答

0

根據你的代碼,我假設你使用GSON進行JSON處理。如果你的JSON元素是一個數組,你可以簡單地使用get(index)來訪問它的元素。草繪在這裏:

//Not taking care of possible null values here 
JsonObject rootobj = ... 
JsonElement elem = rootobj.get("names"); 
if (elem.isJsonArray()) { 
    JsonArray elemArray = elem.getAsJsonArray(); 

    JsonElement innerElem = elemArray.get(0); 
    if (innerElem.isJsonArray()) { 
     JsonArray innerArray = innerElem.getAsJsonArray(); 
     //Now you can access the elements using get(..) 
     //E.g. innerArray.get(2); 
    } 
} 

當然這不是很好看。您還可以查看JsonPath,它簡化了瀏覽到JSON文檔中的特定部分。

更新: 在您提到的文檔中,您想要精確地提取哪個值?數組元素的id值(根據您的評論之一)?這可能是這樣做的this這裏舉例:

JsonElement root = jp.parse.... 
JsonArray rootArray = root.getAsJsonArray(); //Without check whether it is really an array 
//By the following you would extract the id 6104546 
//Access an other array position if you want the second etc. element 
System.out.println(rootArray.get(0).getAsJsonObject().get("id")); 

否則請你想要什麼更詳細的解釋(你貼不與JSON例子匹配你的代碼參考)。

+0

我不知道你是否因爲我的文章更新而收到更新。因此,我更新了我的文章,評論。 – MDDCoder25

0

在你的Github鏈接中,你的根元素是一個數組,而不是一個對象。 (而且也沒有names屬性)

所以你需要

root.getAsJsonArray(); 

那麼你會遍歷數組的長度,並使用get(i),訪問特定對象。

從該對象,請使用其他方法獲取訪問它的一個屬性