티스토리 뷰

728x90
반응형

 

json파일 읽어서 map으로 변환하기

 

 

1. pom.xml 에 라이브러리 추가

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

 

2. json파일을 불러와서 Map<String, Object> 형태로 변환해 리턴해주는 메소드를 생성합니다.

// 파일 불러와서 Map<String, Object> 형태로 변환해 리턴해주는 메소드
public Map<String, Object> getJsonFile(String fileName) throws IOException, ParseException{
    JSONParser parser = new JSONParser();
    // JSON 파일 읽을 경로 
    String BASE_PATH = new File("").getAbsolutePath();
	String FILE_PATH = BASE_PATH + fileName;
    // JSON 파일 읽기
    Reader reader = new FileReader(FILE_PATH);

    // reader를 Object로 parse
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(reader); 

    JSONObject jsonObj = null;
    try{
        jsonObj = (JSONObject)obj;
        map.put("data", jsonObj);
    }catch(Exception e) {  // List로 시작하는 파일일 경우
        JSONArray jsonArr = (JSONArray)obj;
        map.put("data", jsonArr);
    }
        
    return map;
}

 

3. 메소드를 호출하여 사용합니다.

Map<String, Object> map = getJsonFile("data.json");
System.out.println(map);
728x90
반응형
댓글