2

I'm trying to exclude the possibility of a json field to be modificated at HTTP.POST operation. This is my class:

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserModel {

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Long userId;

    @NotNull
    private String username;

    private RoleModel role;

    @NotNull
    private String email;

    @NotNull
    private String firstName;

    @NotNull
    private String secondName;

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

    @JsonProperty(access = JsonProperty.Access.READ_ONLY)
    private Date registrationDate;
}

I want for example the property userId to be accessible only for read (http get). I've tried with @JsonProperty but it doesn't work, instead it works for the password field. (this property is visible only for write/ post).

Can you please tell me where I'm wrong? or if there is a more elegant way to do that?

Many thanks,

Rapidistul
  • 406
  • 4
  • 9
  • 19
  • [This](https://stackoverflow.com/questions/21920367/why-when-a-constructor-is-annotated-with-jsoncreator-its-arguments-must-be-ann) should help. – Andrew S Feb 15 '18 at 18:16
  • Thanks, @AndrewS, I'm still looking for another solution. As you can see I use lombok and I don't want to write constructors for domain classes. – Rapidistul Feb 15 '18 at 19:52

1 Answers1

2

You can achieve such thing with @JsonView annotation:

// Declare views as you wish, you can also use inheritance.
// GetView also includes PostView's fields 
public class View {
    interface PostView {}
    interface GetView extends PostView {}
}

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class UserModel {

    @JsonView(View.GetView.class)
    private Long userId;

    @JsonView(View.PostView.class)
    @NotNull
    private String username;
    ....
}

@RestController
public class Controller {

    @JsonView(View.GetView.class)
    @GetMapping("/")
    public UserModel get() {
        return ... ;
    }

    @JsonView(View.PostView.class)
    @PostMapping("/")
    public UserModel post() {
        return ... ;
    }

...
}

For more information: https://spring.io/blog/2014/12/02/latest-jackson-integration-improvements-in-spring

Ghokun
  • 3,345
  • 3
  • 26
  • 30