Sample Code

 avatar
unknown
java
2 years ago
1.5 kB
3
Indexable
package com.maheshtkumaran;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.json.simple.parser.JSONParser;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.StringReader;


public class Main {

    public static void main(String[] args) {
        String filePath = "/Users/mttamils/IdeaProjects/HelloWorld/src/com/maheshtkumaran/sample.json";
        // Read the JSON file as String!
        String fileContents = readJSONFile(filePath);
        // Convert the JSON String to JSON Array.
        JsonArray dataArr = parseJSONArray(fileContents);
        System.out.println(dataArr);
    }


    public static String readJSONFile(String filePath){
        JSONParser parser = new JSONParser();
        try {
            FileReader reader = new FileReader(filePath);
            /* always wrap the FileReader in BufferedReader */
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line = null;
            String contents = "";
            while((line = bufferedReader.readLine()) != null)
            {
                contents = contents + line;
            }
            bufferedReader.close();
            return contents;
        } catch(Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static JsonArray parseJSONArray(String contents){
        JsonArray jobj =  new Gson().fromJson(new StringReader(contents), JsonArray.class);
        return jobj;
    }
}


Editor is loading...