Read json

By | April 13, 2015
Share the joy
  •  
  •  
  •  
  •  
  •  
  •  

I have following json file and folder structure.

A maven dependency I need is following:

<dependency>
    <groupId>com.googlecode.json-simple</groupId>
    <artifactId>json-simple</artifactId>
    <version>1.1.1</version>
</dependency>

By following colde. I read the json file from it:

package com.pli.project.test;

import org.apache.commons.io.IOUtils;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import java.io.*;
import java.util.HashMap;

/**
 * Created by lipeng on 2015/4/4.
 */
public class App {

    public static void main(String[] args) {
        JSONParser parser = new JSONParser();
        try{
            //find json file in resources folder
            ClassLoader classLoader = App.class.getClassLoader();
            InputStream is = classLoader.getResourceAsStream("client_secret.json");
            BufferedReader br = new BufferedReader((new InputStreamReader(is)));
            Object obj = parser.parse(br);
            //read json file
            JSONObject jsonObject = (JSONObject)obj;
            HashMap<String, String> web = (HashMap<String, String>)jsonObject.get("web");
            String client_secret = web.get("client_secret");
            System.out.println(client_secret);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}