1

Say I've got an object User:

@JsonView(User.Activity.class)
String name
@JsonView(User.Activity.class)
int id
String description;
// Realistically there will be a lot more fiels here...
... getters and setters

And I've then gone and created one:

User u = new User();
u.setName("xoxo");
u.setId(1);
u.setDescription("DESCRIPTION....");
dao.save(u);

return u.withJsonView(User.Activity.class); // Is there a way to apply this?

I want to return this object to the client with the fields from a specific JsonView. How can I do this?

Edit

Hashmap hm = new Hashmap();
MappingJacksonValue value = new MappingJacksonValue(user);
value.setSerializationView(User.Activity.class);
hm.put("success", value);

return ResponseEntity.ok(hm); // Returns whole user object :\

That is all I'm doing. value ends up being the whole user object, even though I've only put the User.activity.class view on a couple of fields. I'm then simply returning the hashmap in a responseentity

Community
  • 1
  • 1
James111
  • 15,378
  • 15
  • 78
  • 121
  • Yes it is. Another reason why I want to apply a view after creating an object is so I can insert only the data I need into elasticsearch and not the whole object! @CássioMazzochiMolin It'd be amazing if there was something like djangos serialization but for hibernate/jpa objects! – James111 Sep 14 '16 at 09:00
  • You are returning a `HashMap` in the `ResponseEntity` instead of return the `MappingJacksonValue` instance. – cassiomolin Sep 14 '16 at 09:29

1 Answers1

1

To apply a view, use the @JsonView annotation on the endpoint method:

@GetMapping
@JsonView(User.Activity.class)
public User getUser() {
    User user = new User();
    return user;
}

To apply a view dynamically, wrap your POJO into a MappingJacksonValue:

@GetMapping
public MappingJacksonValue getUser(){
    User user = new User();
    MappingJacksonValue value = new MappingJacksonValue(user);
    value.setSerializationView(User.Activity.class);
    return value;
}

For more details, check this post about Jackson integration in Spring.

cassiomolin
  • 124,154
  • 35
  • 280
  • 359
  • It doesn't seem to work! It just returns the whole object – James111 Sep 14 '16 at 09:16
  • I added the neccesary code. The endpoint is simply returning a response entity. – James111 Sep 14 '16 at 09:26
  • 1
    Ahh silly me. I was thinking that the serialisation occurred at `value.setSerializationView` and that adding the value into the hashmap would have the serialized view! – James111 Sep 14 '16 at 09:32