Rafael
Rafael

Reputation: 585

deserializing entities with relationships

We receive JSON that looks like:

{ name: "john", surname: "smith", company: "1234342" }

Our Client Side framework can also handle relationships between objects and company is mapped to its ID.

We have an Hibernate Customer entity, which has a Company member which is a relationship to another Company entity.

We use Spring's @RequestMapping method(@RequestBody Customer c) to process requests and deserialize Entities, but we fail to deserialize the provided JSON. Hibernate does not know how to build a Company from a String, regardless of the fact that the String is its primary key.

It is very easy to serialize entities from Hibernate into JSON, but deserialization seems a different story.

Is there any pattern/construct to handle what we want to achieve? Can anybody point me in the right direction?

Upvotes: 2

Views: 2204

Answers (2)

Prasanna
Prasanna

Reputation: 3781

I think Dozer would be ideal to do such serialization/deserialization. If you receive the JSON structure as a map then you can tell dozer to convert that map to a corresponding entity object.

Upvotes: 0

skaffman
skaffman

Reputation: 403591

The simplest solution is to have two separate class models, one for Hibernate and one for JSON, and convert between them as necessary.

It's not very elegant, though, so Jackson (which is the the JSON implementation used by Spring) provides an extension mechanism (called Modules), which in turn allows you to register custom deserialization logic (i.e. how to turn JSON tokens into java objects). Have a look at that, see if it works for you.

You;d then have to configure Jackson in the Spring context to use the custom mapper.

Upvotes: 2

Related Questions