Home



2018/07 - Reading JSON Data in Java

Hi folks,

This will be a short guide on how to read JSON data using Java. This is more of a "how to" guide on how one would begin to setup their own JSON reader, but I hope it'll be of some use to someone out there. We'll be using Java 8, Apache Commons 3.7 and the JSON in Java Jar file. Find the github repo here.

Firstly, start a new project and save this as a JSON file in your package (make a package and call it whatever you want):

 


   {  
      "number":"67"
   },
   {  
      "number":"45"
   },
   {  
      "number":null
   },
   {  
      "number":"45"
   },
   {  
      "number":"s"
   },
   {  
      "number":"-3"
   },
   {  
      "number":"12"
   },
   {  
      "number":"100"
   },
   {  
      "number":"3"
   }
]

 

Save it as "data.json". You might have noticed that it looks like an array of key value pairs, because it is cool

We're going to use the "key" to grab all of the values and place them into a list of Integers. Do do that, create two new classes (The code to read and transform the data, and another to run the program):

The runner:

import java.util.List;

public class TestRunner {
    
    public static void main(String args[]) {
        JsonParser jspr = new JsonParser();
        List<Integer> listOfNums = null;
        try {
            listOfNums = jspr.readFromFile("src\\laffan\\marc\\data.json");
            System.out.println(listOfNums);
        } catch (Throwable e) {
            e.printStackTrace();
        }
                                             
    }

}

The actual reader:

import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.math.NumberUtils;
import org.json.JSONArray;
import org.json.JSONTokener;

public class JsonParser {

    public List<Integer> readFromFile(String filePath) throws Throwable {
        JSONTokener tokener;
        List<Integer> custNumEntList = new ArrayList<Integer>();
        try {
            tokener = new JSONTokener(new FileReader(filePath));   
            JSONArray jsonArray = new JSONArray(tokener);
            
            for(int current = 0; current < jsonArray.length(); current++) {
                try {
                    String numString = (String) jsonArray.getJSONObject(current).get("number").toString();
                    if(!NumberUtils.isCreatable(numString)) {
                        throw new NumberFormatException("Non-numeric data (" + numString + ")");
                    }
                    custNumEntList.add(new Integer(numString));
                }
                catch(Exception e) {
                    System.out.println("Could not read data row. The following data was not added: " + e.getMessage());
                }
                
            }
        }
        catch (Throwable t) {
            System.out.println("Could not read file");
            t.printStackTrace();
            throw t;            
        }
        
        return custNumEntList;
    }
    
}
 

 

You should find that by running the TestRunner class, you'll see the JSON data printed in your console. Of course you'll need to have your data file in the right location and have the two JAR files I mentioned above installed correctly too.

Good luck,

Marc