Używanie tylko @JsonIgnore podczas serializacji, ale nie deserializacja

Mam obiekt user, który jest wysyłany do i z serwera. Kiedy wysyłam obiekt user, nie chcę wysyłać hashowanego hasła do klienta. Dodałem więc @JsonIgnore Na właściwości password, ale to również blokuje go przed deserializacją do hasła, co utrudnia rejestrację użytkowników, gdy nie mają hasła.

Jak mogę uzyskać tylko @JsonIgnore, Aby zastosować się do serializacji, a nie deserializacji? Używam Spring JSONView więc nie mam dużej kontroli nad ObjectMapper.

Things I ' ve tried:

  1. Dodaj {[0] } do nieruchomości
  2. Dodaj @JsonIgnore tylko do metody getter
Author: pb2q, 2012-09-20

5 answers

Dokładnie jak to zrobić zależy od wersji Jacksona, której używasz. To zmieniło się wokół wersji 1.9, wcześniej można było to zrobić dodając @JsonIgnore do gettera.

Które próbowałeś:

Dodaj @JsonIgnore tylko na metodzie getter

Wykonaj to, Oraz Dodaj specyficzną adnotację @JsonProperty dla nazwy pola JSON "password" do metody setter dla hasła obiektu.

Nowsze wersje Jacksona mają dodano argumenty READ_ONLY i WRITE_ONLY dla JsonProperty. Więc możesz też zrobić coś w stylu:

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

Dokumenty można znaleźć tutaj .

 329
Author: pb2q,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-27 17:52:01

Aby to osiągnąć, potrzebujemy tylko dwóch adnotacji:

  1. @JsonIgnore
  2. @JsonProperty

Użyj @JsonIgnore na członku klasy i jego getterze. Użyj @JsonProperty na jego seterze.

Przykładowa ilustracja mogłaby w tym pomóc:

class User{

// More fields here
 @JsonIgnore
 private String password;

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

 @JsonProperty
 public void setPassword(String password) {
    this.password = password;
 }
}
 75
Author: Balaji Boggaram Ramanarayan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-19 02:26:55

Od wersji 2.6: bardziej intuicyjnym sposobem jest użycie adnotacji com.fasterxml.jackson.annotation.JsonProperty w polu:

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

Nawet jeśli istnieje getter, wartość pola jest wyłączona z serializacji.

JavaDoc says:

/**
 * 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

Jeśli potrzebujesz tego na odwrót, użyj Access.READ_ONLY.

 54
Author: Daniel Beer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-08 20:32:48

W moim przypadku Jackson automatycznie serializuje / deserializuje obiekty, które zwracam z kontrolera Spring MVC (używam @RestController Z Spring 4.1.6). Musiałem użyć com.fasterxml.jackson.annotation.JsonIgnore zamiast org.codehaus.jackson.annotate.JsonIgnore, w przeciwnym razie po prostu nic nie zrobił.

 9
Author: Alex Beardsley,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-22 15:45:53
"user": {
        "firstName": "Musa",
        "lastName": "Aliyev",
        "email": "[email protected]",
        "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
                }
 2
Author: Musa,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-01 11:13:20