反序列化具有关系的实体 [英] deserializing entities with relationships

查看:145
本文介绍了反序列化具有关系的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们收到的JSON如下所示:

  {name:john,姓:smith,公司: 1234342} 

我们的客户端框架还可以处理对象与公司之间的关系,并将其映射到其ID。



我们有一个Hibernate Customer实体,它有一个与另一个公司实体有关系的公司实体。

我们使用Spring的 @RequestMapping方法(@RequestBody Customer c)来处理请求并反序列化实体,但是我们无法反序列化提供的JSON。 Hibernate并不知道如何从String中构建公司,无论String是它的主键。



将Hibernate中的实体序列化为JSON,但反序列化似乎是另一回事。



是否有任何模式/构造来处理我们想要实现的内容?任何人都可以指向正确的方向吗?

解决方案

最简单的解决方案是有两个独立的类模型,一个用于Hibernate和一个对于JSON,并在必要时在它们之间进行转换。



虽然不是很优雅,但是Jackson(它是Spring使用的JSON实现)提供了一种扩展机制称为模块),这反过来又允许你注册自定义反序列化逻辑(即如何将JSON标记转换为java对象)。看看这个,看看它是否适合你。



然后你必须在Spring上下文中配置Jackson以使用自定义映射器。 / p>

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?

解决方案

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.

这篇关于反序列化具有关系的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆