如何在Java程序中从JSON获取值?

时间:2012-08-10 14:21:10

标签: java json

我是JSON的初学者......

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

  

{ “查询”:{ “页”:{ “3037904”:{ “的pageid”:3037904, “NS”:0, “标题”: “凯宾斯基”,   “类别”:[{“ns”:14,“title”:“类别:公司成立于1897年”},{“ns”:14,“title”:“Category:Hotel chains”},{“ns”: 14,“标题”:“类别:凯宾斯基酒店”}}}}}}

我试过

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”。

2 个答案:

答案 0 :(得分: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应该是一个由多个这样的对象组成的数组。

答案 1 :(得分: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"));