How to I add a springframework/fasterxml hook for pre/post JSON serialisation?

13 Views Asked by At

I have a JPA entity A that I want to serialize into JSON using springframework annotations.

The entity has a (non identifying) foreign key, so in the JPA, this is an object B.

  1. I want our angular front-end to be able to create these entities, which means that the JSON coming from the front end needs to contain the key

  2. I want to send object A to the angular front end, without pulling in the whole of object B - just the key.

I have therefore created in the JPA entity A an object b of type B and a field bKey of type String and mapped both to column B_KEY. I have marked then as being updatable false and insertable false, but JPA is still complaining that I have a duplicate column.

So, I am thinking of adding a @Transient property bKey which is not managed by JPA at all. This property would be populated just before serialzation to JSON, and unpacked (bRegistry.findById(bkey)) on deserialization.

I'd like to do this without having to write a whole serializer, which looks like it is a bit of a rabbit-hole.

Is there a @PreJsonSerialization / @PostJsonDeserialization kind of thing in fasterxml? I haven't found it.

Failing that - what base class do I extend for use with @JSonSerialize? I would prefer not to have to write the serializer by hand, writing out each field in code.

Alternatively, is there a "when you convert this to JSON, just send the key columns, not the whole object"?

0

There are 0 best solutions below