Spring MVC에서 JSON으로 보내는 동안 Java 객체의 필드를 동적으로 무시 private String emailId;

최대 절전 모드를 위해 이와 같은 모델 클래스가 있습니다.

@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {

    private Integer userId;
    private String userName;
    private String emailId;
    private String encryptedPwd;
    private String createdBy;
    private String updatedBy;

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "UserId", unique = true, nullable = false)
    public Integer getUserId() {
        return this.userId;
    }

    public void setUserId(Integer userId) {
        this.userId = userId;
    }

    @Column(name = "UserName", length = 100)
    public String getUserName() {
        return this.userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    @Column(name = "EmailId", nullable = false, length = 45)
    public String getEmailId() {
        return this.emailId;
    }

    public void setEmailId(String emailId) {
        this.emailId = emailId;
    }

    @Column(name = "EncryptedPwd", length = 100)
    public String getEncryptedPwd() {
        return this.encryptedPwd;
    }

    public void setEncryptedPwd(String encryptedPwd) {
        this.encryptedPwd = encryptedPwd;
    }

    public void setCreatedBy(String createdBy) {
        this.createdBy = createdBy;
    }

    @Column(name = "UpdatedBy", length = 100)
    public String getUpdatedBy() {
        return this.updatedBy;
    }

    public void setUpdatedBy(String updatedBy) {
        this.updatedBy = updatedBy;
    }
}

Spring MVC 컨트롤러에서 DAO를 사용하여 객체를 얻을 수 있습니다. JSON 객체로 반환합니다.

@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
    @ResponseBody
    public User getUser(@PathVariable Integer userId) throws Exception {

        User user = userService.get(userId);
        user.setCreatedBy(null);
        user.setUpdatedBy(null);
        return user;
    }
}

보기 부분은 AngularJS를 사용하여 수행되므로 다음과 같이 JSON을 얻습니다.

{
  "userId" :2,
  "userName" : "john",
  "emailId" : "john@gmail.com",
  "encryptedPwd" : "Co7Fwd1fXYk=",
  "createdBy" : null,
  "updatedBy" : null
}

암호화 된 암호를 설정하지 않으려면 해당 필드도 null로 설정합니다.

그러나 나는 이것을 원하지 않으며 모든 필드를 클라이언트 측에 보내고 싶지 않습니다. password, updatedby, createdby 필드를 보내지 않으려면 결과 JSON은 다음과 같아야합니다.

{
  "userId" :2,
  "userName" : "john",
  "emailId" : "john@gmail.com"
}

다른 데이터베이스 테이블에서 오는 클라이언트로 보내지 않으려는 필드 목록입니다. 따라서 로그인 한 사용자에 따라 변경됩니다. 어떻게해야합니까?

제 질문을 받으 셨기를 바랍니다.



답변

@JsonIgnoreProperties("fieldname")POJO에 주석을 추가하십시오 .

또는 @JsonIgnoreJSON을 역 직렬화하는 동안 무시하려는 필드의 이름 앞에 사용할 수 있습니다 . 예:

@JsonIgnore
@JsonProperty(value = "user_password")
public String getUserPassword() {
    return userPassword;
}

GitHub 예


답변

나는 내가 파티에 조금 늦었다는 것을 알고있다. 그러나 나는 실제로 이것도 몇 달 전에 만났다. 사용 가능한 모든 솔루션이 나에게 그다지 매력적이지 않았기 때문에 (믹신? ugh!) 결국이 프로세스를 더 깔끔하게 만들기 위해 새 라이브러리를 만들었습니다. 누구나 시도해보고 싶다면 https://github.com/monitorjbl/spring-json-view 에서 사용할 수 있습니다 .

기본 사용법은 매우 간단하며 다음 JsonView과 같이 컨트롤러 메서드에서 객체 를 사용합니다 .

import com.monitorjbl.json.JsonView;
import static com.monitorjbl.json.Match.match;

@RequestMapping(method = RequestMethod.GET, value = "/myObject")
@ResponseBody
public void getMyObjects() {
    //get a list of the objects
    List<MyObject> list = myObjectService.list();

    //exclude expensive field
    JsonView.with(list).onClass(MyObject.class, match().exclude("contains"));
}

Spring 외부에서도 사용할 수 있습니다.

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import static com.monitorjbl.json.Match.match;

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addSerializer(JsonView.class, new JsonViewSerializer());
mapper.registerModule(module);

mapper.writeValueAsString(JsonView.with(list)
      .onClass(MyObject.class, match()
        .exclude("contains"))
      .onClass(MySmallObject.class, match()
        .exclude("id"));

답변

동적으로 할 수 있습니까?

보기 클래스 만들기 :

public class View {
    static class Public { }
    static class ExtendedPublic extends Public { }
    static class Internal extends ExtendedPublic { }
}

모델에 주석 달기

@Document
public class User {

    @Id
    @JsonView(View.Public.class)
    private String id;

    @JsonView(View.Internal.class)
    private String email;

    @JsonView(View.Public.class)
    private String name;

    @JsonView(View.Public.class)
    private Instant createdAt = Instant.now();
    // getters/setters
}

컨트롤러에서 뷰 클래스 지정

@RequestMapping("/user/{email}")
public class UserController {

    private final UserRepository userRepository;

    @Autowired
    UserController(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @RequestMapping(method = RequestMethod.GET)
    @JsonView(View.Internal.class)
    public @ResponseBody Optional<User> get(@PathVariable String email) {
        return userRepository.findByEmail(email);
    }

}

데이터 예 :

{"id":"5aa2496df863482dc4da2067","name":"test","createdAt":"2018-03-10T09:35:31.050353800Z"}

답변

JsonProperty.Access.WRITE_ONLY속성을 선언하는 동안 액세스를 설정하여이를 수행 할 수 있습니다 .

@JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
@SerializedName("password")
private String password;

답변

@JsonInclude(JsonInclude.Include.NON_NULL)클래스와 @JsonIgnore암호 필드에 추가 (Jackson이 null 값을 직렬화하도록 강제) 합니다.

물론 @JsonIgnore이 특정 경우뿐만 아니라 항상 then을 무시하고 싶다면 createdBy 및 updatedBy에 설정할 수 있습니다.

최신 정보

POJO 자체에 주석을 추가하고 싶지 않은 경우 Jackson ‘s Mixin Annotations가 좋은 옵션입니다. 문서 확인


답변

예, JSON 응답으로 직렬화되는 필드와 무시할 필드를 지정할 수 있습니다. 이것은 동적으로 속성 무시를 구현하기 위해 수행해야하는 작업입니다.

1) 먼저 com.fasterxml.jackson.annotation.JsonFilter의 @JsonFilter를 엔티티 클래스에 추가해야합니다.

import com.fasterxml.jackson.annotation.JsonFilter;

@JsonFilter("SomeBeanFilter")
public class SomeBean {

  private String field1;

  private String field2;

  private String field3;

  // getters/setters
}

2) 그런 다음 컨트롤러에서 MappingJacksonValue 객체를 생성하고 필터를 설정해야하며 결국이 객체를 반환해야합니다.

import java.util.Arrays;
import java.util.List;

import org.springframework.http.converter.json.MappingJacksonValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import com.fasterxml.jackson.databind.ser.FilterProvider;
import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.fasterxml.jackson.databind.ser.impl.SimpleFilterProvider;

@RestController
public class FilteringController {

  // Here i want to ignore all properties except field1,field2.
  @GetMapping("/ignoreProperties")
  public MappingJacksonValue retrieveSomeBean() {
    SomeBean someBean = new SomeBean("value1", "value2", "value3");

    SimpleBeanPropertyFilter filter = SimpleBeanPropertyFilter.filterOutAllExcept("field1", "field2");

    FilterProvider filters = new SimpleFilterProvider().addFilter("SomeBeanFilter", filter);

    MappingJacksonValue mapping = new MappingJacksonValue(someBean);

    mapping.setFilters(filters);

    return mapping;
  }
}

다음은 응답으로 얻을 수있는 것입니다.

{
  field1:"value1",
  field2:"value2"
}

대신 :

{
  field1:"value1",
  field2:"value2",
  field3:"value3"
}

여기서는 field1 및 field2 속성을 제외한 다른 속성 (이 경우 field3)을 응답으로 무시하는 것을 볼 수 있습니다.

도움이 되었기를 바랍니다.


답변

내가 너 였고 그렇게하고 싶었다면 컨트롤러 계층에서 내 사용자 엔터티를 사용하지 않고 대신 UserDto (데이터 전송 개체)를 만들어 사용하여 비즈니스 (서비스) 계층 및 컨트롤러와 통신합니다. Apache BeanUtils (copyProperties 메소드)를 사용하여 User 엔티티에서 UserDto로 데이터를 복사 할 수 있습니다.