클래스의 모든 필드를 getter 없이도 직렬화

코드 리뷰를 하다가 새로운 사실을 알게 되었다. Jackson은 기본적으로 getter 메소드로 직렬화를 한다. 아래처럼 지정하면 클래스의 필드들을 기반으로 접근제어자 상관 없이 직렬화가 가능하다. OBJECT_MAPPER.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

2024-09-15 · 1 min · 25 words

빈 생성자 만들지 않아도 되는 방법

@ConstructorProperties 어노테이션을 생성자에 붙이면 해결된다. class Employee { private final int id; private final String name; @ConstructorProperties({"id", "name"}) public Employee(int id, String name) { this.id = id; this.name = name; } public int getEmpId() { return id; } public String getEmpName() { return name; } } 참고 자료 https://www.tutorialspoint.com/when-to-use-constructorproperties-annotation-with-jackson-in-java

2024-09-15 · 1 min · 49 words

불변 객체 역직렬화 방법 분석

배경 data class Person(var id: Long? = null, var name: String? = null) fun main() { val objectMapper = ObjectMapper() val person: Person = objectMapper.readValue("{\"id\":1, \"name\": \"junroot\"}", Person::class.java) println(person.name) } ObjectMapper를 통해 역직렬화하는 경우, 기본 생성자를 이용해 객체를 생성한 뒤 자바 리플렉션을 이용해 값을 주입하고 있다. 따라서 기본 생성자가 필요한데 이렇게 되면 프로퍼티들이 불변일 수가 없게된다. @JsonCreator와 @JsonProperty를 통해서 생성 가능하다는 사실을 알게되고 이를 사용했었다. data class Person @JsonCreator constructor( @JsonProperty("id") val id: Long, @JsonProperty("name") val name: String ) fun main() { val objectMapper = ObjectMapper() val person: Person = objectMapper....

2024-09-15 · 2 min · 260 words

snake case 필드를 camel case로 역직렬화 하기

목표 아래와 같이 snake case로 필드가 존재하는 json을 camel case로 역직렬화 하는 방법이 필요했다. { "first_name": "Jackie", "last_name": "Chan" } 방법1: @JsonProperty 사용 @JsonProperty 어노테이션을 사용하면, 해당 필드와 매핑되는 json 프로퍼티의 이름을 지정할 수 있다. public class UserWithPropertyNames { @JsonProperty("first_name") private String firstName; @JsonProperty("last_name") private String lastName; // standard getters and setters } 방법2: @JsonNaming 사용 @JsonNaming을 클래스 위에 명시하면 현재 클래스의 역직렬화 이름 전략을 설정할 수 있다. 아래와 같이 명시하면 클래스의 필드를 json의 snake case로 찾아서 매핑한다....

2024-09-15 · 1 min · 98 words

Jackson byte를 List 형태로 반환하는 법

List<Map<String,Object>> participantJsonList = mapper.readValue(jsonString, new TypeReference<List<Map<String,Object>>>(){}); 참고 자료

2024-09-15 · 1 min · 8 words