如何在JAVA中解析与父子相关的JsonArray?

时间:2015-07-14 14:06:52

标签: java arrays json parsing

这是Json文本。我可以得到姓名,书籍和#34;作为一个数组。但问题是书籍也是一个数组。书籍的内容是以这种形式出现的; {"title:heresometext",paragraphs{value1:heresometext,value2:heresometext}}所以就像数组中的数组一样。像一个父子关系。我想要做的是达到thoose value1,value2,value3字符串分离。



{"data"
 [
  "name" : "Here some text",
  "surname" : "Here some text",
  "books" : [
  {
    "title1" : "Here some text.",
    "paragraphs" : [
    {
        "value1" : "Here some text."
    },
    {
        "value2" : "Here some text."
    }
    ]
  },
  {
    "title2" : "Here some text.",
    "paragraphs" : [
    {
        "value3" : "Here some text.",
        "image1" : "Here some text."
    },
    {
        "value4" : "Here some text."
    },
    {
        "value5" : "Here some text."
    }
    ]
  }
  ]
 ]
}




如何以树形式获取它们,以树形式分隔所有数据,以便能够将它们保存在数据库中。 任何帮助都是有用的



  name: "Here some text",
  surname: "Here some text",
  books:
         - title1 : "Here some text."
             -paragraphs:
                 - value : "Here some text.
                 - value : "Here some text.
         - title2 : "Here some text."
             -paragraphs:
                 - value : "Here some text.
                 - image : "Here some text.




1 个答案:

答案 0 :(得分:1)

我们在项目中使用了JSON.simple。它是一个JSON解析器。

示例:

public class JSONParsingExample {
  public static void main(String[] args) {
    JSONParser parser = new JSONParser();
    try {
      Object obj = parser.parse(new FileReader(parser.getClass().getClassLoader().getResource("jsondata.json").getFile()));
      JSONObject jsonObject = (JSONObject) obj;
      JSONObject data = (JSONObject) jsonObject.get("data");
      JSONArray books = (JSONArray) data.get("books");
      System.out.println(books);
      Iterator<JSONObject> iterator = books.iterator();
      while (iterator.hasNext()) {
        JSONObject book = (JSONObject) iterator.next();
        System.out.println("This books name is " + book.get("name"));
        JSONArray paras = (JSONArray) book.get("paras");
        Iterator<JSONObject> parasI = paras.iterator();
        int i = 0;
        while (parasI.hasNext()) {
          JSONObject para = (JSONObject) parasI.next();
          para.keySet().forEach(o -> System.out.println(o + "/" + para.get(o)));
        }
      }
    } catch (FileNotFoundException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (ParseException e) {
      e.printStackTrace();
    }
  }
}