杰克逊-反序列化为其他类型 [英] Jackson - Deserializing to a Different Type
问题描述
使用Jackson,我如何才能使一个应用程序使用一组类对JSON进行序列化/反序列化,而又让另一个应用程序对相同的JSON反序列化并加载这些类的不同实现?
Using Jackson, how can I have JSON serialized/deserialized by one application using one set of classes, but have another application deserialize the same JSON and load different implementations of those classes?
我有一个(Spring MVC)Web应用程序,该应用程序允许用户定义脚本中的步骤,而脚本又将在客户端应用程序中执行.步骤可能是ShowDialogStep
之类的,具有dialogText
之类的属性,或者是WaitStep
其具有duration
之类的属性.
I have a (Spring MVC) web application that allows users to define steps in a script, that in turn will be executed in a client application. Steps might be things like ShowDialogStep
, with properties like dialogText
, or WaitStep
with a property of duration
.
客户端应用程序将从服务器加载步骤集合.但是,由客户端实例化的类需要具有特定于执行的功能,例如execute()
,在WaitStep
的情况下,该功能将跟踪其等待的时间.显然,服务器端应用程序永远不需要知道这一点,在不那么琐碎的示例中,步骤的执行/更新逻辑涉及各种特定于客户端的依赖关系.
The client application will load collections of steps from the server. However, the classes instantiated by the client need to have execution-specific functionality like execute()
, which in the case of WaitStep
will keep a track of how far through waiting it is. Clearly the server-side application never needs know about this, and in less trivial examples the execute/update logic of a steps involves all manner of client-specific dependencies.
因此,我需要回顾一下:
So, to recap I need:
- 用于将原型"类映射到JSON的服务器应用程序;
- 读取 same JSON的客户端应用程序,但实例化特定于执行的类,而不是原型"类.
- The server application to map the 'prototype' classes to JSON;
- The client application to read the same JSON but instantiate execution-specific classes instead of the 'prototype' ones.
这是否可以在客户端映射器上进行配置,如果JSON是使用相对的类名(而不是完全限定的)进行序列化的,则可以将反序列化器配置为在不同的程序包中查找实现里面有执行逻辑?
Would this be something that could be configured on the client-side mapper, perhaps if the JSON was serialized using relative class names (rather than fully-qualified) then the deserializer could be configured to look in a different package for the implementations with execution logic in them?
推荐答案
您可以使用以下方法:
在服务器端:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.PROPERTY, property="@type")
class Prototype {
...
}
objectMapper.registerSubtypes(
new NamedType(Prototype.class, "Execution"),
...
);
然后它将序列化一个Prototype实例并添加一种bean:
then it will serialize a Prototype instance and add a type of bean:
{
"@type" : "Execution",
...
}
在客户端:
@JsonTypeInfo(use=JsonTypeInfo.Id.NAME,
include=JsonTypeInfo.As.PROPERTY, property="@type")
class Execution {
...
}
objectMapper.registerSubtypes(
new NamedType(Execution.class, "Execution"), // the same name
....
);
objectMapper.readValue(....); // will be deserialized to an Execution instance
这篇关于杰克逊-反序列化为其他类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!