티스토리 뷰
728x90
반응형
@JsonProperty
JSON 데이터의 필드 이름과 Java 객체의 필드 이름이 다를 때 매핑을 도와줍니다.
주로 직렬화(Serialization, Java 객체 → JSON) 및 역직렬화(Deserialization, JSON → Java 객체) 시 사용됩니다.
import com.fasterxml.jackson.annotation.JsonProperty;
public class User {
@JsonProperty("user_name") // JSON에서 "user_name"을 Java 객체에서 name 필드에 매핑
private String name;
@JsonProperty("user_age") // JSON에서 "user_age"를 Java 객체에서 age 필드에 매핑
private int age;
// 기본 생성자 (필수)
public User() {}
public User(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public int getAge() { return age; }
public void setAge(int age) { this.age = age; }
}
읽기/쓰기 전용 속성 설정
@JsonProperty에 access 속성을 사용하면 직렬화/역직렬화의 방향을 설정
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonProperty.Access;
public class Product {
@JsonProperty(value = "product_id", access = Access.READ_ONLY) // JSON → Java (읽기 전용)
private int id;
@JsonProperty(value = "product_name", access = Access.WRITE_ONLY) // Java → JSON (쓰기 전용)
private String name;
public Product() {}
public Product(int id, String name) {
this.id = id;
this.name = name;
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
camelCase snake_case 자동 변환
Spring에서 Jackson은 기본적으로 camelCase를 snake_case로 변환하지 않습니다.
자동 변환하려면 Jackson ObjectMapper 설정이 필요
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE);
@JsonAlias
@JsonProperty는 JSON의 특정 필드 이름을 Java 필드와 매핑하는데 사용됨.
@JsonAlias는 JSON에서 여러 개의 필드 이름을 Java 필드 하나로 매핑할 때 사용됨.
import com.fasterxml.jackson.annotation.JsonAlias;
public class Person {
@JsonAlias({"first_name", "fname"}) // JSON에서 first_name 또는 fname으로 들어와도 name 필드에 매핑됨
private String name;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
728x90
반응형
'Java' 카테고리의 다른 글
[Java] Generic (0) | 2025.03.03 |
---|---|
[Java] try-with-resources (0) | 2025.03.01 |
[Java] OpenCSV (0) | 2025.01.26 |
[Java] record (0) | 2025.01.12 |
[Java] Lombok @UtilityClass (0) | 2025.01.12 |
반응형
300x250