4

I have UI object that wraps JPA entity and in constructor of that UI object I do lazy loading of some properties. In that same constructor I need to know what JsonView is currently active so I dont lazy load some fields that are not needed if say its the List view. Is there way to find out from constructor what is current active JsonView at runtime. Or is there any other way to achieve what I described above.

My current plan create custom serializer that during serialization will call setJsonView(Class jsonView) of the object that it serializes. All my objects that serialized will have to support that method. Inside that metid I can do lazy loading based on now known json view. Something like this:

public class JsonViewSerializer extends JsonSerializer<BaseSerializableEntity> {

  @Override
  public void serialize(BaseSerializableEntity value, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
    value.setJsonView(provider.getSerializationView());
    // need to pass serialization to base class...
  }

}
Andrei V
  • 1,468
  • 3
  • 17
  • 32

1 Answers1

4

Currently active view is accessible via context object (SerializerProvider or DeserializationContext), using method getActiveView().

StaxMan
  • 113,358
  • 34
  • 211
  • 239
  • So how do I get SerializerProvider from within constructor? – Andrei V Oct 09 '15 at 22:00
  • There is no way to do that. You will need to determine view from within serialize() method of serializer, during serialization. – StaxMan Oct 12 '15 at 20:31
  • Thank you. I outlined my solution up top. Only part that unclear is how to call base class serializer function serialize. I only want to inject something into value object and pass control back to base. – Andrei V Oct 12 '15 at 21:53
  • @AndreiV that is bit more complicated, depending on how you register your serializer. If it's registered for a type, you can not simply look up "original" one (since you replaced it, effectively). But instead of registering like that, you could use `BeanSerializerModifier` (registered via Module), to obtain original serializer, keep reference to it, construct and return custom one. If so, just make sure to implement `ContextualSerializer`, delegate that call. – StaxMan Oct 13 '15 at 18:36
  • I see. Thank you for your help StaxMan. – Andrei V Oct 14 '15 at 14:34