按名称Java获取JSON对象值

时间:2015-07-10 09:00:09

标签: java json

我的JSON数据看起来像这样:

[
  "{\"pid\":\"1\",\"title\":\"New CEO announced\",\"titleirish\":\"CEO nua\",\"content\":\"Bernard Byrne has been announced as the new CEO. Rejoice!\",\"contentirish\":\"Is Bernard Byrne an CEO. B\\\\u00edg\\\\u00ed s\\\\u00e1sta!\",\"imageurl\":\"http:\\\\\\/\\\\\\/scoiluiriada.ie\\\\\\/wp-content\\\\\\/uploads\\\\\\/2014\\\\\\/02\\\\\\/IMG_1781-150x112.jpg\",\"category\":\"News\",\"publishedby\":\"Andy\",\"modified\":\"2015-07-01 16:21:13\",\"buildings\":\"Bankcentre,Hume House,Time House\"}",
  "{\"pid\":\"2\",\"title\":\"New CTO pronounced\",\"titleirish\":\"CEO nua\",\"content\":\"Bernard Byrne has been announced as the new CEO. Rejoice!\",\"contentirish\":\"Is Bernard Byrne an CEO. B\\\\u00edg\\\\u00ed s\\\\u00e1sta!\",\"imageurl\":\"http:\\\\\\/\\\\\\/scoiluiriada.ie\\\\\\/wp-content\\\\\\/uploads\\\\\\/2014\\\\\\/02\\\\\\/IMG_1781-150x112.jpg\",\"category\":\"News\",\"publishedby\":\"Andy\",\"modified\":\"2015-07-02 10:09:10\",\"buildings\":\"Hume House\"}",
   ....

到目前为止,我有以下代码:

    JSONParser parser = new JSONParser();
    try {
        Object obj = parser.parse(allData); // allData = JSON String above
        JSONArray nitems = (JSONArray)obj;

这给了我一个我要解析的所有对象的数组。 (它完美地运作)

现在,循环遍历此数组,我想获取对象成员值。 像这样:

nitems.get(0).getValueOf("title") // should return "New CEO announced"
nitems.get(0).getValueOf("titleirish")  // "CEO Nua"      etc.

这显然不起作用,我会用什么代码代替。

提前感谢您的任何答案。

1 个答案:

答案 0 :(得分:1)

修正了一些评论的帮助。这是解决方案:

JSONObject obj2 = (JSONObject)new JSONParser().parse(nitems.get(i).toString());
System.out.println(obj2.get("title").toString());