[Java] Gson을 사용하여 Json 파일을 읽어 객체로 변환하기

Donghyun Kim·2023년 3월 17일

Goal

Spring 프로젝트 내부에 resources 디렉토리에 저장된
Json 파일을 읽어와 객체로 변환하기

Json 파일 읽기

FileWriter 객체를 사용하여 디렉토리에 저장된 파일을 읽어올 수 있지만
이경우 경로가 조금이라도 바뀔 경우 경로를 수정해줘야해서
ClassPathResource 객체를 통하여 resources 파일을 참조하게 하는 방법이 더 좋다.

FileWriter 객체를 통한 파일 읽기

FileWriter file = new FileWriter("c:/data/test.json");

ClassPathResoucre 객체를 통한 파일 읽기

ClassPathResource resource = new ClassPathResource("test.json");

Json 파일 내용 String 변환

ClassPathResource의 getInputStream 메서드를 통해 byte형태의 File Stream을 읽어와 String으로 변환

byte[] byteData = FileCopyUtils.copyToByteArray(resource.getInputStream());

String data = new String(byteData, StandardCharsets.UTF_8);

Gson을 사용하여 객체로 변환

Gson gson = new Gson();

# data의 Type은 String이여야 한다.
gson.fromJson(data, Object.class);
profile
"Hello World"

0개의 댓글