개발일기/Spring

Gson을 이용한 json 파일 읽기

길동이이이잉 2024. 4. 10. 04:19
728x90
반응형
  • json 파일이 한 줄로 되어있지 않고 띄어쓰기가 되어 있을 경우
File file = new File(fileUpDownService.getFileLocation().toString() + "/cellLine/CellLineInhibitor.json");

try {
        BufferedReader br = new BufferedReader(new FileReader(file));
				Gson gson = new Gson();

//이 부분을 추가해준다
        String inputLine;
        StringBuilder sb = new StringBuilder();
        while ((inputLine = br.readLine()) != null) {
            sb.append(inputLine);
        }

        List<Object> json = gson.fromJson(sb.toString(), List.class);

        System.out.println(json);
    }catch (IOException e){
         e.printStackTrace();
    }

 

 

  • json 파일이 한 줄로 되어있는 경우
File file = new File(fileUpDownService.getFileLocation().toString() + "/cellLine/CellLineInhibitor.json");

try {

    BufferedReader br = new BufferedReader(new FileReader(file));
    Gson gson = new Gson();
    List<Object> json = gson.fromJson(br.readLine(), List.class);
//json 파일의 형태에 따라 
//Map<String, String> kinaseListJson = gson.fromJson(result, LinkedHashMap.class);
//Map<String, List<String>> pdbCode = gson.fromJson(result, LinkedHashMap.class);
//Map<String, ArrayList<String>> json = gson.fromJson(br.readLine(), LinkedHashMap.class);
//Map<String, ArrayList<ArrayList<String>>> json = gson.fromJson(br.readLine(), LinkedHashMap.class);

//type 이 지정 되는 경우
//Type type = new TypeToken<Map<String, Set<String>>>(){}.getType(); // type 지정
//Map<String, Set<String>> chains = gson.fromJson(result, type);

//이런 예시도 있음

    System.out.println(json);

}catch (IOException e){

    e.printStackTrace();

}
728x90
반응형