Reputation: 4105
I try to serialize a lazily (fetch type) populated entity coming from JPA (Jakarta Persistence API, Hibernate implementation) in JSON with JSON-B (Jakarta JSON Binding, Yasson implementation):
@ManyToOne(fetch = FetchType.LAZY)
private MyJpaEntity o;
I know that the instances of org.hibernate.proxy.LazyInitializer
must not be serialized, I used this workaround with Jackson: @JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
, it produced clean JSON values not containing those fields.
I tried to obtain the same result with JSON-B by using a custom PropertyVisibilityStrategy
but it didn't work, Jakarta JSON was still trying to serialize the Hibernate interceptor. However, it seemed to be the way to go as I wanted to ignore the property.
At last, I serialized the lazy initializer as null
, I got rid of the JsonbException, but the property hibernateLazyInitializer
is still in the JSON values:
public static final class DumbLazyInitializerSerializer implements JsonbSerializer<LazyInitializer> {
@Override
public void serialize(final LazyInitializer li, final JsonGenerator jg, final SerializationContext sc) {
jg.writeNull();
}
}
try (final Jsonb jsonb = JsonbBuilder.create(new JsonbConfig().withSerializers(new DumbLazyInitializerSerializer()))) {
// do your own stuff
}
Is there a smart way of getting rid of the exception and the unwanted field in the resulting JSON? There's an issue about this problem but it provides no working solution. Changing the fetch type to EAGER
isn't an option in my case as it would cause some performance problems.
Upvotes: 0
Views: 78