source

시리얼라이제이션 중에 @JsonIgnore만 사용하고, 시리얼라이제이션 해제하지 않음

goodcode 2022. 9. 18. 21:34
반응형

시리얼라이제이션 중에 @JsonIgnore만 사용하고, 시리얼라이제이션 해제하지 않음

서버 간에 송수신되는 사용자 개체가 있습니다.사용자 개체를 보낼 때 해시된 암호를 클라이언트에 보내고 싶지 않습니다.이렇게 덧붙였습니다.@JsonIgnore패스워드 속성에서는 패스워드로의 역직렬화가 차단되기 때문에 패스워드가 없는 경우 사용자 등록이 어려워집니다.

★★★★★★★★★★★★★★★★★★★★★★★★★@JsonIgnore디시리얼라이제이션이 아닌 시리얼라이제이션에 적용할 수 있습니까?는 Spring 때문에, Spring JSONView를 할 수 ObjectMapper.

내가 시도한 것:

  1. @JsonIgnore
  2. @JsonIgnore만의 Getter

정확한 방법은 사용 중인 Jackson 버전에 따라 다릅니다.기능은 버전 1.9에서 변경되었으며, 그 이전 버전에서는 다음을 추가하여 이 작업을 수행할 수 있습니다.@JsonIgnore★★★★★★★★★★★★★★★★★★.

당신이 시도했던 것:

getter 메서드에만 @JsonIgnore 추가

작업을 수행하고 특정 항목을 추가합니다.@JsonPropertyJSON "password" 필드 이름에 대한 주석을 객체의 암호에 대한 설정기 메서드에 추가합니다.

버전은 Jackson을 추가했다.READ_ONLY ★★★★★★★★★★★★★★★★★」WRITE_ONLY, ""의 주석 인수JsonProperty따라서 다음과 같은 작업을 수행할 수도 있습니다.

@JsonProperty(access = JsonProperty.Access.WRITE_ONLY)
private String password;

문서는 여기에서 찾을 수 있습니다.

그러기 위해서는 다음 두 개의 주석만 있으면 됩니다.

  1. @JsonIgnore
  2. @JsonProperty

@JsonIgnore 와 그 " " " " " " " " 。@JsonProperty 설명하면 이 됩니다예를 들어 설명하면 도움이 됩니다.

class User {

    // More fields here
    @JsonIgnore
    private String password;

    @JsonIgnore
    public String getPassword() {
        return password;
    }

    @JsonProperty
    public void setPassword(final String password) {
        this.password = password;
    }
}

2: 은 "2.6"을 사용하는 것입니다.com.fasterxml.jackson.annotation.JsonProperty드드: :

@JsonProperty(access = Access.WRITE_ONLY)
private String myField;

getter가 존재하는 경우에도 필드 값은 시리얼라이제이션에서 제외됩니다.

Java Doc 설명:

/**
 * Access setting that means that the property may only be written (set)
 * for deserialization,
 * but will not be read (get) on serialization, that is, the value of the property
 * is not included in serialization.
 */
WRITE_ONLY

할 때는 , 쓰다, 쓰다, 쓰다, 쓰다, 쓰다.Access.READ_ONLY.

제 경우 Spring MVC 컨트롤러에서 반환된 오브젝트를 잭슨에게 자동으로 시리얼(디)하도록 하고 있습니다(@RestController를 Spring 4.1.6에서 사용하고 있습니다). 수 ★★★★★★★★★★★★★★★★★★★★★★★.com.fasterxml.jackson.annotation.JsonIgnoreorg.codehaus.jackson.annotate.JsonIgnore다른 이유와 마찬가지로, 그것은 아무 것도 하지 않았다.

하나의 은 '인수'를입니다.allowSetters=true를 참조해 주세요.이렇게 하면 비밀번호를 dto로 역직렬화할 수 있지만 contains object를 사용하는 응답 본문에는 시리얼화되지 않습니다.

예:

@JsonIgnoreProperties(allowSetters = true, value = {"bar"})
class Pojo{
    String foo;
    String bar;
}

다.foo ★★★★★★★★★★★★★★★★★」bar오브젝트에는 입력되지만 응답 본문에는 foo만 입력됩니다.

"user": {
        "firstName": "Musa",
        "lastName": "Aliyev",
        "email": "klaudi2012@gmail.com",
        "passwordIn": "98989898", (or encoded version in front if we not using https)
        "country": "Azeribaijan",
        "phone": "+994707702747"
    }

@CrossOrigin(methods=RequestMethod.POST)
@RequestMapping("/public/register")
public @ResponseBody MsgKit registerNewUsert(@RequestBody User u){

        root.registerUser(u);

    return new MsgKit("registered");
}  

@Service
@Transactional
public class RootBsn {

    @Autowired UserRepository userRepo;

    public void registerUser(User u) throws Exception{

        u.setPassword(u.getPasswordIn());
        //Generate some salt and  setPassword (encoded -  salt+password)
        User u=userRepo.save(u);

        System.out.println("Registration information saved");
    }

}

    @Entity        
@JsonIgnoreProperties({"recordDate","modificationDate","status","createdBy","modifiedBy","salt","password"})
                    public class User implements Serializable {
                        private static final long serialVersionUID = 1L;

                        @Id
                        @GeneratedValue(strategy=GenerationType.AUTO)
                        private Long id;

                        private String country;

                        @Column(name="CREATED_BY")
                        private String createdBy;

                        private String email;

                        @Column(name="FIRST_NAME")
                        private String firstName;

                        @Column(name="LAST_LOGIN_DATE")
                        private Timestamp lastLoginDate;

                        @Column(name="LAST_NAME")
                        private String lastName;

                        @Column(name="MODIFICATION_DATE")
                        private Timestamp modificationDate;

                        @Column(name="MODIFIED_BY")
                        private String modifiedBy;

                        private String password;

                        @Transient
                        private String passwordIn;

                        private String phone;

                        @Column(name="RECORD_DATE")
                        private Timestamp recordDate;

                        private String salt;

                        private String status;

                        @Column(name="USER_STATUS")
                        private String userStatus;

                        public User() {
                        }
                // getters and setters
                }

클래스 레벨에서 @JsonIgnoreProperties를 사용하여 json에서 원하는 변수를 "value" 파라미터에 넣을 수 있습니다.나한테는 잘 먹혔어.

@JsonIgnoreProperties(value = { "myVariable1","myVariable2" })
public class MyClass {
      private int myVariable1;,
      private int myVariable2;
}

다음과 같은 작업을 수행할 수도 있습니다.

@JsonIgnore
@JsonProperty(access = Access.WRITE_ONLY)
private String password;

나는 효과가 있다

언급URL : https://stackoverflow.com/questions/12505141/only-using-jsonignore-during-serialization-but-not-deserialization

반응형