[spring] VO에서 특정 변수 리턴에 대해 제어하는 방법
나의 경우 공통 VO(model)를 사용하지만 API 마다 다른 json의 형태로 리턴해야 하는 경우 사용했다.
1. pom.xml 에 json-view dependency 추가(최신버전 확인하여 사용)
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>json-view</artifactId>
<version>1.0.1</version>
</dependency>
2. 사용 예제
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.monitorjbl.json.JsonView;
import static com.monitorjbl.json.Match.match;
import com.monitorjbl.json.JsonViewSerializer;
@Autowired
private UserService userService;
// jackson 초기화
ObjectMapper mapper = new ObjectMapper().registerModule(new JsonViewModule());
// 데이터 조회
List<UserVO> userList = userService.selectUser();
// 제외할 fields 지정
String json = mapper.writeValueAsString(JsonView.with(userList).onClass(UserVO.class, match().exclude("gender")));
.exclude("필드명") 을 여러번 반복해서 사용 가능
.exclude("data.user.gender") 와 같은 식으로 접근 가능
3. json 생성시 항상 제외되기를 원하는 경우 VO의 변수에 @JsonIgnore Jackson어노테이션을 사용
class UserVO {
@JsonIgnore
private String password;
@JsonIgnore
public String getPassword() {
return password;
}
@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
public void setPassword(final String password) {
this.password = password;
}
}
변수, getter, setter 레벨에서 각각 지정하는 것도 가능
참고 사이트
https://github.com/monitorjbl/json-view
monitorjbl/json-view
Programmatic JSON views with Jackson. Contribute to monitorjbl/json-view development by creating an account on GitHub.
github.com
Only using @JsonIgnore during serialization, but not deserialization
I have a user object that is sent to and from the server. When I send out the user object, I don't want to send the hashed password to the client. So, I added @JsonIgnore on the password property, ...
stackoverflow.com
Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType
This page will walk through Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType annotations example. These annotations are used to ignore logical properties in JSON serialization and deserialization.
www.concretepage.com
https://medium.com/@circlee7/jackson-annotations-19886933a252
Jackson annotations
json관련 jackson 에서 지원하는 유용한 어노테이션 기능들을 살펴보자
medium.com