Pages

Ads 468x60px

Sunday, July 22, 2012

Java: Read JSON files using com.google.gson


This program will read all JSON files placed in a directory e.g. 'json'. You can modify this code easily for your specific JSON file. I used com.google.gson for this purpose so please include its JAR file in your project to run this program. Gson will facilitate you so well to handle JSON objects and arrays. You can download this file from the following link
http://code.google.com/p/google-gson/downloads/list.
If there is any confusion, please let me know... :)


import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.Map.Entry;

public class ReadJSON {

    final private String path = "json/"; //set directory path
    private JsonParser parser = new JsonParser();
    private int count = -1;

    public static void main(String[] args) {
        ReadJSON read = new ReadJSON();
        read.sendJSONFile();
    }

    //send json files to read one by one
    private void sendJSONFile() {

        File[] jsonfiles = getJSONFiles();

        if (jsonfiles.length > 0) {
            for (int i = 0; i <= count; i++) {

                try {
                    //prints json file names
                    System.out.println("File: \t" + jsonfiles[i]);
                    JsonElement jsonElement = parser.parse(new FileReader(jsonfiles[i]));
                    JsonObject jsonObject = jsonElement.getAsJsonObject();
                    readJSONFile(jsonObject);
                }
                catch (FileNotFoundException e) {
                    System.out.println(e.getMessage());
                    //e.getStackTrace();
                }
                catch (IOException e) {
                    System.out.println(e.getMessage());
                    //e.getStackTrace();
                }
                catch (Exception e) {
                    System.out.println(e.getMessage());
                    //e.getStackTrace();
                }

            }
        }
    }

    //read a complete json file
    private void readJSONFile(JsonObject jsonObject) {

        for (Entry<String, JsonElement> entry : jsonObject.entrySet()) {

            String key = entry.getKey();
            JsonElement value = entry.getValue();

            if (value.isJsonObject()) {
                readJSONFile(value.getAsJsonObject());
            }
            else if (value.isJsonArray()) {
                 JsonArray jsonArray = value.getAsJsonArray();
           
                 if (jsonArray.size() == 1) {
                    readJSONFile((JsonObject) jsonArray.get(0));
                }
                 else {
                    //prints json array name
                    System.out.println(key);
                    Iterator<JsonElement> msg = jsonArray.iterator();
                    while (msg.hasNext()) {
                        ////prints json array values
                        System.out.println(msg.next());
                    }
                }
            }
            else {
                ////prints json object's keys and values
                System.out.println(key + " - " + value);
            }
        }
    }

    //get only .json files from a directory
    private File[] getJSONFiles() {

        File folder = new File(path);
        File[] files = folder.listFiles();
        File[] jsonfiles = new File[files.length];

        for (int i = 0; i < files.length; i++) {

            if (files[i].isFile()) {
                if (files[i].getName().endsWith(".json") || files[i].getName().endsWith(".JSON")) {
                    jsonfiles[++count] = files[i];
                }
            }
        }

        return files;
    }
}

5 comments:

  1. Mashallah Butt sahb. Your blog came into my knowledge while I was searching for JSON. Great article

    ReplyDelete
  2. Hello,
    Thank you for this code.
    I have a JSON file to read in java and when i copy/past your code and execute it, it gave me a java.lang.NullPointerException .
    What can the error be?
    Thank you

    ReplyDelete
  3. Use this, to read a single JSON File:

    import com.google.gson.JsonArray;
    import com.google.gson.JsonElement;
    import com.google.gson.JsonObject;
    import com.google.gson.JsonParser;
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.FileReader;
    import java.util.Iterator;
    import java.util.Map.Entry;

    public class ReadFile {

    final private String path = "json/product.json"; // set directory path
    private JsonParser parser = new JsonParser();

    public static void main(String[] args) {
    ReadFile read = new ReadFile();
    read.sendToRead();
    }

    // send json file to read
    private void sendToRead() {

    File jsonfile = new File(path);

    try {
    JsonElement jsonElement = parser.parse(new FileReader(jsonfile));
    JsonObject jsonObject = jsonElement.getAsJsonObject();
    readJSONFile(jsonObject);
    } catch (FileNotFoundException e) {
    System.out.println(e.getMessage());
    // e.getStackTrace();
    } catch (Exception e) {
    System.out.println(e.getMessage());
    // e.getStackTrace();
    }
    }

    // read a complete json file
    private void readJSONFile(JsonObject jsonObject) {

    for (Entry entry : jsonObject.entrySet()) {

    String key = entry.getKey();
    JsonElement value = entry.getValue();

    if (value.isJsonObject()) {
    System.out.println(key + ":");
    readJSONFile(value.getAsJsonObject());
    } else if (value.isJsonArray()) {
    JsonArray jsonArray = value.getAsJsonArray();

    if (jsonArray.size() == 1) {
    readJSONFile((JsonObject) jsonArray.get(0));
    } else {
    // prints json array name
    System.out.println(key);
    Iterator msg = jsonArray.iterator();
    while (msg.hasNext()) {
    // //prints json array values
    System.out.println(msg.next());
    }
    }
    } else {
    // //prints json object's keys and values
    System.out.println(key + " - " + value);
    }
    }
    }

    ReplyDelete