Java 为除根节点之外的所有节点注册Jackson序列化程序
我有一个元素结构,它们都实现了接口“Urifyable”。假设我们有火车和现在的车站Java 为除根节点之外的所有节点注册Jackson序列化程序,java,jackson,dropwizard,Java,Jackson,Dropwizard,我有一个元素结构,它们都实现了接口“Urifyable”。假设我们有火车和现在的车站 public class Train implements Urifyable { @JsonProperty public String getName() { return "My Train"; } @JsonProperty public Station getCurrentStation() { return StationPoo
public class Train implements Urifyable {
@JsonProperty
public String getName() {
return "My Train";
}
@JsonProperty
public Station getCurrentStation() {
return StationPool.get("1");
}
public String getUri() {
return "/train/1";
}
}
public class Station implements Urifyable {
@JsonProperty
public String getName() {
return "My Station";
}
@JsonProperty
public Train[] getCurrentTrains() {
return /* some code to get an array of trains */;
}
public String getUri() {
return "/station/1";
}
}
如果我将其用于dropwizard+jason+jax rs,我可以注册如下自定义序列化程序:
final SimpleModule myModule = new SimpleModule("MyModule");
myModule.addKeySerializer(Urifyable.class, new UrifyableSerializer());
environment.getObjectMapper().registerModule(myModule);
UrifyableSerializer不阻止jackson的通用序列化逻辑,只返回getUri方法的字符串表示形式
如何仅为除根节点之外的所有对象启用此序列化程序?因为现在它会回来
"/station/1"
如果我请求电台,但它应返回:
{
"name": "My Station",
"currentTrains": [
"/train/1",
"/train/2",
"/train/3",
]
}
{
"name": "My Train",
"currentStation": "/station/1"
}
对于“/train/1”,它应该返回:
{
"name": "My Station",
"currentTrains": [
"/train/1",
"/train/2",
"/train/3",
]
}
{
"name": "My Train",
"currentStation": "/station/1"
}
一种可能是指定用于属性的序列化程序,而不是类型。也就是说,您不是通过模块注册,而是这样声明:
public class Station implements Urifyable {
// note: since it's array, use 'contentUsing'; for POJOs it'd be 'using'
@JsonSerialize(contentUsing=MyTrainSerializer.class)
public Train[] getCurrentTrains() {
return /* some code to get an array of trains */;
}
}
这种方式序列化程序仅适用于通过特定POJO属性实现的值的序列化。您可以将
currentTrains
字段定义为列表而不是列表,而不是使用特殊的序列化程序。实际上,我并不100%确定这是否可行,也不确定Jackson是否会崩溃,或者只是使用getUri
进行序列化。