1

我是一个关于 JSON 的初学者......

如何从 Java 程序中的以下 JSON 对象中获取“3037904”的值?

{"query":{"pages":{"3037904":{"pageid":3037904,"ns":0,"title":"Kempinski", "categories":[{"ns":14,"title ":"Category:1897 年成立的公司"},{"ns":14,"title":"Category:连锁酒店"},{"ns":14,"title":"Category:Kempinski Hotels"}] }}}}

我尝试过了

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

2 回答 2

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应该是多个此类对象的数组。

于 2012-08-10T14:27:41.533 回答
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"));
于 2012-08-10T14:24:59.150 回答