Convert JSON inside an array list to an ArrayList (Java)

北战南征 提交于 2019-12-24 10:44:25

问题


My output looks like this :

{
  "IssueField1":{
                 "id":"customfield_10561", 
                 "name":"Bug Disclaimer", 
                 "type":null, 
                 "value":"<div style>...</div>"
                }, 

  "IssueField2":{
                 "id":"customfield_13850", 
                 "name":"ENV Work Type (DT)", 
                 "type":null, 
                 "value":null
                }, 
   .
   .
   .

  "IssueField9":{
                 "id":"timespent",
                 "name":"Time Spent", 
                 "type":"null", 
                 "value":"null"
                 }
}

I want to create an ArrayList and and add all names in it if the value is not null. Any idea how should I do this in Java ?


回答1:


Lets say you have the following json object:

{ "name":"john doe", "age":100, "job":"scientist", "addresses":["address 1","address 2","address 3"] }

to get the different fields inside of the object, create a JSONParser object and use the get() method to get the value held in that field

    try {
        FileReader reader = new FileReader("/path/to/file.json");
        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(reader);
        String name = (String) jsonObject.get("name");
        System.out.println("The name is " + name);
        long age = (long) jsonObject.get("age");
        System.out.println("The age is: " + age);
        JSONArray lang = (JSONArray) jsonObject.get("addresses");
        for (int i = 0; i < lang.size(); i++) {
            System.out.println("Address " + (i + 1) + ": " + lang.get(i));
        }
    } catch (FileNotFoundException fileNotFound) {
        fileNotFound.printStackTrace();
    } catch (IOException io) {
        io.printStackTrace();
    } catch (NullPointerException npe) {
        npe.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    }
}


来源:https://stackoverflow.com/questions/31928400/convert-json-inside-an-array-list-to-an-arraylist-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!