230627 TIL #122 GSON

김춘복·2023년 6월 26일
0

TIL : Today I Learned

목록 보기
122/494

230627 Today I Learned

Java에서 JSON 형식을 다루기 위해 GSON 라이브러리를 사용해 봤다.


GSON 공식문서

GSON

Java 객체를 JSON 형식으로 변경시킬 때 사용하는 자바 라이브러리

  • gradle 의존성 추가
dependencies {
    implementation 'com.google.code.gson:gson:2.10.1'
}
  • 객체 생성 방법
// 기본 설정으로 간단하게 생성해 사용
Gson gson1 = new Gson();
// 추가적인 설정 가능
Gson gson2 = new GsonBuilder().create();
  • JSON 생성
Gson gson = new Gson();
JsonObject jsonObject = new JsonObject();
jsonObject.addProperty("name", "ChoonB");
jsonObject.addProperty("age", 4);

String str = gson.toJson(jsonObject);
System.out.println(str); // {"name":"ChoonB","age":4}
  • Object -> JSON 변환
public class Cat{
	private String name;
    private int age;
    
    public Cat(String name, int age) {
    	this.name = name;
        this.age = age;
    }
}

public class Main {
 
    public static void main(String[] args) {
    	Cat cat = new Cat("ChoonB", 4);
        
        // Gson 객체 생성
        Gson gson = new Gson();
        
        // Cat 객체 -> JSON 문자열로 변환
        String catJson = gson.toJson(cat);
        System.out.println(cat); // {"name":"ChoonB","age":4}
        
    }
  • 기타 JSON 포맷 양식 설정
// new Gson()이 아니라 new GsonBuilder()로 생성해야 설정이 가능하다.
    Gson gson = new GsonBuilder()
    	// camelCase인 필드명을 snake_case로 변경 가능
    	.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
        // 기본적으로 null인 값들은 출력되지 않지만 아래 설정시 null 값도 표시
        .serializeNulls()
        .create();
profile
꾸준히 성장하기 위해 매일 log를 남깁니다!

0개의 댓글