如何使用Json.simple解析Java中的JSONArray?

时间:2013-09-16 15:36:39

标签: java json arrays

我尝试读取这样的JSON文件:

{
  "presentationName" : "Here some text",
  "presentationAutor" : "Here some text",
  "presentationSlides" : [
  {
    "title" : "Here some text.",
    "paragraphs" : [
    {
        "value" : "Here some text."
    },
    {
        "value" : "Here some text."
    }
    ]
  },
  {
    "title" : "Here some text.",
    "paragraphs" : [
    {
        "value" : "Here some text.",
        "image" : "Here some text."
    },
    {
        "value" : "Here some text."
    },
    {
        "value" : "Here some text."
    }
    ]
  }
  ]
}

对于学校的练习,我选择尝试使用JSON.simple(来自GoogleCode),但我对另一个JSON库开放。我听说过Jackson和Gson:他们比JSON.simple好吗?

这是我当前的Java代码:

        Object obj = parser.parse(new FileReader( "file.json" ));

        JSONObject jsonObject = (JSONObject) obj;

        // First I take the global data
        String name = (String) jsonObject.get("presentationName");
        String autor = (String) jsonObject.get("presentationAutor");
        System.out.println("Name: "+name);
        System.out.println("Autor: "+autor);

        // Now we try to take the data from "presentationSlides" array
        JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides");
        Iterator i = slideContent.iterator();

        while (i.hasNext()) {
            System.out.println(i.next());
            // Here I try to take the title element from my slide but it doesn't work!
            String title = (String) jsonObject.get("title");
            System.out.println(title);
        }

我查了很多例子(一些在Stack中!)但我从来没有找到解决问题的方法。

也许我们不能用JSON.simple做到这一点?你推荐什么?

3 个答案:

答案 0 :(得分:14)

您永远不会为jsonObject分配新值,因此在循环内它仍然引用完整的数据对象。我想你想要的东西:

JSONObject slide = i.next();
String title = (String)slide.get("title");

答案 1 :(得分:14)

它正在运作! Thx Russell。我将完成我的练习,并尝试GSON来看看差异。

这里有新代码:

        JSONArray slideContent = (JSONArray) jsonObject.get("presentationSlides");
        Iterator i = slideContent.iterator();

        while (i.hasNext()) {
            JSONObject slide = (JSONObject) i.next();
            String title = (String)slide.get("title");
            System.out.println(title);
        }

答案 2 :(得分:-1)

对于Gson,您可以在此处粘贴json文件:https://www.freecodeformat.com/json2pojo.php 创建适当的pojo类,然后使用以下代码:

Gson gson = new Gson();

    try (Reader reader = new FileReader("pathToYourFile.json")) {

        // Convert JSON File to Java Object
        Root root = gson.fromJson(reader, Root.class);

        // print staff you need
        System.out.println(root.getCommands().get(0).getName());

    } catch (IOException e) {
        e.printStackTrace();
    }