反序列化具有关系的实体
我们收到的 JSON 如下所示:
{ name: "john", surname: "smith", company: "1234342" }
我们的客户端框架还可以处理对象之间的关系,并将公司映射到其 ID。
我们有一个 Hibernate Customer 实体,它有一个 Company 成员,该成员与另一个 Company 实体有关系。
我们使用 Spring 的 @RequestMapping 方法(@RequestBody Customer c) 来处理请求并反序列化实体,但我们无法反序列化提供的 JSON。 Hibernate 不知道如何从字符串构建 Company,无论字符串是其主键。
将实体从 Hibernate 序列化为 JSON 非常容易,但反序列化似乎是另一回事。
是否有任何模式/结构来处理我们想要实现的目标?有人能指出我正确的方向吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最简单的解决方案是拥有两个单独的类模型,一种用于 Hibernate,一种用于 JSON,并根据需要在它们之间进行转换。
但它不是很优雅,因此 Jackson(Spring 使用的 JSON 实现)提供了一种扩展机制(称为 Modules ),这又允许您注册自定义反序列化逻辑(即如何转换 JSON 令牌)转换为 java 对象)。看看它,看看它是否适合你。
然后你必须 在 Spring 上下文中配置 Jackson 以使用自定义映射器。
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.
我认为 Dozer 是进行此类序列化/反序列化的理想选择。如果您收到 JSON 结构作为映射,那么您可以告诉 dozer 将该映射转换为相应的实体对象。
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.