Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading from a Json file and copying the data into a list

I would like to read from a json file like:

{
   "name": "Luis Lopez",
   "name": "Armando Guascogne Ursular",
   "name": "Brancar Diego"
}

read from the json file and copy the names into an array list. I tried like this:

public List getName() {
        try {
            Object obj = parser.parse(new FileReader("mypath\name.json"));
            JSONObject jsonObject = (JSONObject) obj;
            String name = (String) jsonObject.get("name");
            for (int i = 0; i<jsonObject.length();i++){
                datasource.add(name);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return datasource;
}

But it returns me the empty list.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

First of all, your JSON is not valid, as you’re using the same key name 3 times. This will give you in any case only the last key, Brancar Diego as response in general.

So, you have to do two things:

  • restructure your JSON
  • adapt your code (if required)

A JSON restructure could look like so:

{
"names": ["Luis Lopez", "Armando Guascogne Ursular", "Brancar Diego"]
}

In other words, your JSON must contain unique elements, with the above example you’d define a JSON array correctly, which then could be iterated over.

Afterwards, you’d have to adapt your Java Code accordingly.

public List<String> getName() {
    List<String> names = new ArrayList<>();
    try {
        Object obj = parser.parse(new FileReader("mypath\name.json"));
        JSONObject jsonObject = (JSONObject) obj;
        JSONArray nameArray = (JSONArray) jsonObject.get("names");
        for (int i = 0; i < nameArray.length(); i++) {
            names.add((String) nameArray.get(i));
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return names;
}

If you, for whatever reason are not able to change the JSON, you should instead cache each iteration with a unique ID, create a new ArrayList element with these IDs or just populate they keys by Auto Increment and iterate over it again after you’ve formatted it, but that’d be a performance decrease + bad practice + hard to maintain, so I’d not really recommend it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading