2012-08-10 36 views
1

我是一個非常初學JSON的人...如何在Java程序中從JSON中獲取值?

如何從Java程序中的以下JSON對象中獲取「3037904」的值?

{ 「查詢」:{ 「頁」:{ 「3037904」:{ 「的pageid」:3037904, 「NS」:0, 「標題」: 「凱賓斯基」, 「類別」:[{」 ns「:14,」title「:」類別:1897年成立的公司「},{」ns「:14,」title「:」Category:Hotel chains「},{」ns「:14,」title「類別:凱賓斯基酒店「}]}}}}

我試圖

JSONObject query = json.getJSONObject("query"); 
int pages = query.getInt("pages"); 

但它需要

"{"3037904":{"pageid":3037904,"ns":0,"title":"Kempinski", 
"categories":[{"ns":14,"title":"Category:Companies established in 1897"},{"ns":14,"title":"Category:Hotel chains"},{"ns":14,"title":"Category:Kempinski Hotels"}]}}}}", 

不僅「3037904」。

回答

4

你需要做一些更多的工作與你的JSONObject

在這個答案我會假設你想得到那pageid價值。

我們只能假設在嵌套pageid的存在 - 在特定級別:

// "query" is the top-level object: 
JSONObject query = json.getJSONObject("query"); 
// "pages" is a field of "query" 
JSONObject pages = query.getJSONObject("pages"); 

// these will hold the object with the value that you want, and that value: 
JSONObject nestedObject = null; 
int pageId = 0; 

// these are the property names in the "pages" object: 
String[] keys = pages.getNames(pages); 

// iterate over the keys in the "pages" object, looks for JSONObjects: 
for (int i = 0; i < keys.length; i++) 
{ 
    try 
    { 
     nestedObject = pages.getJSONObject(keys[i]); 
     // only consider objects with a "pageid" key, stop at the first one: 
     if (nestedObject.has("pageid")) 
      break; 
    } 
    catch (JSONException je) 
    { ; } 
} 

if (nestedObject != null) 
    pageId = nestedObject.getInt("pageid"); 

你的JSON輸入似乎特別之處在於,第一嵌套的對象有一個pages領域,包含另一個對象。複數名稱,pages和嵌套對象 - 將包含該對象的鍵作爲pageid重複對象該對象 - 建議pages應該是包含多個此類對象的數組。

0

看看在GSON庫:http://code.google.com/p/google-gson/

這裏是很好的例子:https://sites.google.com/site/gson/gson-user-guide#TOC-Primitives-Examples

Gson gson = new Gson(); 

Map map = gson.fromJson("{\"query\":{\"pages\":{\"3037904\":{\"pageid\":3037904,\"ns\":0,\"title\":\"Kempinski\", \"categories\":[{\"ns\":14,\"title\":\"Category:Companies established in 1897\"},{\"ns\":14,\"title\":\"Category:Hotel chains\"},{\"ns\":14,\"title\":\"Category:Kempinski Hotels\"}]}}}}", HashMap.class); 

Map query = (Map) map.get("query"); 
Map pages = (Map) query.get("pages"); 
System.out.println(pages.keySet()); 

Map page = (Map) pages.get("3037904"); 
System.out.println(page); 
System.out.println(page.get("pageid"));