본문 바로가기
스터디/Spring

[Spring] @JsonProperty와 @SerializedName

by zoodi 2023. 8. 19.
728x90

 

 

1. Gson과 Jackson

  • Jackson
    • Jackson은 JSON 구조를 처리해주는 라이브러리입니다.
    • json뿐만 아니라 xml도 지원합니다.
  • Gson
    • Gson은 자바에서 json을 파싱하고 생성하기 위해 사용하는 구글에서 개발한 오픈소스입니다.
    • Java Object → Json 문자열, Json 문자열 → Java Object로 변환할 수 있습니다.

 

2. @JsonProperty 사용하기

 

POST로 넘어오는 Json 데이터는 스네이크 케이스로 이루어져있는 반면 자바 엔티티는 카멜 케이스로 이루어져있습니다.

이러한 경우 컨트롤러 단에서 Json ↔ 자바 엔티티를 맵핑 시켜주어도 데이터의 key가 달라지는 경우 제대로 값을 받아오지 못 할 수 있습니다.

이를 해결하기 위해 @JsonProperty를 사용합니다.

 

 

- Student.class

public class Student {
	@JsonProperty("my_id")
    private int id;
	@JsonProperty("my_name")
    private String name;
 
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}
  • @JsonProperty 어노테이션을 통해 json 변환 시 받을 key의 값을 설정합니다.
  • 클라이언트와 서버의 표기법이 달라서 발생하는 문제를 해결합니다.

 

그런데  필드가 많아지면 모든 필드에 @JsonProperty 어노테이션을 적용해주어 코드도 길어지는 우려가있습니다. 이럴때 사용하는 것이 @JsonNaming 입니다.

  • 예제 코드
@JsonNaming(value = PropertyNamingStrategies.SnakeCaseStrategy.class)
public class Student {

    private int id;
    private String name;
 
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

@JsonNaming은 클래스에 사용하여 전체 멤버변수를 새로 네이밍해줍니다.

value에 원하는 case 전략 클래스를 입력해줍니다.

 

 

3. @SerializedName 사용하기

3.1 Gson 라이브러리 추가하기

  • 아래와 같이 dependency를 추가합니다.
//maven
<dependency>
  <groupId>com.google.code.gson</groupId>
  <artifactId>gson</artifactId>
  <version>2.8.7</version>
</dependency>

//gradle
dependencies {
  implementation 'com.google.code.gson:gson:2.8.7'
}

3.2 Java object -> Json 변환 하기 (직렬화, Serialized)

//Student.class
public class Student {
    private int id;
    private String name;
 
    public Student(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + "]";
    }
}

//object to json으로 변환
public class ObjectToJson {
 
    public static void main(String[] args) {
 
        // Student 객체 생성
        Student student = new Student(1, "Anna");
 
        // Gson 객체 생성
        Gson gson = new Gson();
 
        // Student 객체 -> Json 문자열
        String studentJson = gson.toJson(student);
 
        // Json 문자열 출력
        System.out.println(studentJson);  // {"id":1,"name":"Anna"}
    }
}
  • Student 객체를 Json으로 변환합니다.
  • 이때 gson.toJson 메서드를 적용합니다.

 

3.3 Json  -> Java Object 변환 하기 (역직렬화, Deserialized)

public class JsonToObject {
    public static void main(String[] args) {
 
        // Json 문자열
        String jsonStr = "{\"id\":1,\"name\":\"Anna\"}";
 
        // Gson 객체 생성
        Gson gson = new Gson();
 
        // Json 문자열 -> Student 객체
        Student student = gson.fromJson(jsonStr, Student.class);
 
        // Student 객체 toString() 출력
        System.out.println(student); // Student [id=1, name=Anna]
    }
}
  • Json 문자열을 Student 객체로 변환합니다.
  • gson.fromJson 메서드를 적용합니다.

 

 

4. @SerializedName 으로 특정 field 이름 바꾸기

객체로 json 문자열을 생성하거나, json 문자열을 객체로 변환할 때 @SerializedName 어노테이션을 사용하여 특정 필드의 이름을 원하는 이름으로 바꾸어 맵핑합니다.

  • Person.class
public class Person {
 	@SerializedName("personId")
    private int id;
 	@SerializedName("personName")
    private String name;
 
    public Person(int id, String name) {
        this.id = id;
        this.name = name;
    }
 
    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + "]";
    }
 
}
 // 1. Person 객체를 Json 문자열로 변환
Person person = new Person(1, "애나");
String jsonStr = gson.toJson(person);
 
// 결과 출력
System.out.println(jsonStr); // {"personId":1,"personName":"애나"}
 
 
 // 2. Json 문자열을 Person 객체로 변환
String str = "{\"personId\":2,\"personName\":\"김\"}";
Person person2 = gson.fromJson(str, Person.class);
 
System.out.println(person2); // Person [id=2, name=김]
  • Person → Json
    • id 대신 persionId 프로퍼티가 생성
    • name 대신 personName 프로퍼티가 생성
  • Json → Person
    • Json 문자열의 personId 프로퍼티 값을 Person 객체의 id 필드에 맵핑
    • Json 문자열의 personName 프로퍼티 값을 Person 객체의 name 필드에 맵핑

 

 

5. 정리

  • Jackson을 이용할 경우 @JsonProperty 를 사용한다
  • Gson을 이용할 경우 @SerializedName 을 사용한다.

 

6. 참고

https://hianna.tistory.com/629

https://mommoo.tistory.com/83

https://prohannah.tistory.com/87

 

 

728x90

댓글