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

2022-09-03 09:44:22

我正在尝试读取如下所示的 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做到这一点?你有什么建议?


答案 1

您永远不会将新值赋给 ,因此在循环中,它仍然引用完整的数据对象。我想你想要这样的东西:jsonObject

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

答案 2

它正在工作!拉塞尔。我将完成我的练习并尝试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);
        }