카테고리 없음

[SpringBoot][api][json] @JsonIgnore

키보드발 2022. 9. 18. 13:04

@JsonIgnore어노테이션이 붙은 필드는 json으로 출력시에 무시된다.

https://www.tutorialspoint.com/jackson_annotations/jackson_annotations_jsonignore.htm

 

Jackson Annotations - @JsonIgnore

Jackson Annotations - @JsonIgnore @JsonIgnore is used at field level to mark a property or list of properties to be ignored. Example - @JsonIgnore import java.io.IOException; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.

www.tutorialspoint.com

    //@JsonIgnore 미사용
    {
        "id": 2,
        "name": "meber2",
        "address": {
            "city": "부산",
            "zipcode": "test2",
            "street": "2222"
        },
        "orders": []
    }
    //JsonIgnore 사용
    {
        "id": 1,
        "name": "member1",
        "address": {
            "city": "서울",
            "zipcode": "1111",
            "street": "test"
        }
@Entity
@Getter@Setter
public class Member {
    @Id
    @GeneratedValue
    @Column(name = "member_id")
    private Long id;
    private String name;
    @Embedded
    private Address address;
    
    
    @JsonIgnore
    @OneToMany(fetch = FetchType.LAZY,mappedBy = "member")
    private List<Order> orders = new ArrayList<>();


}

✔ 서비스에 따라 수 많은 요구 사항이 있을텐데 엔티티에 @JsonIgnore을 사용하여 Json으로 출력하는 것을 방지하는 것은 옳지 않고 대응도 할 수 없다.

따라서 해당 서비스가 요구하는 정보에 맞는 DTO를 설계후 엔티티에서 데이터를 DTO에 삽입 후 api사용자에게 보내는 것이 현명한 방법이다.

 

✔ 단 무한루프 방지를 위해 JsonIgnore을 사용할 수 있다.