【发布时间】:2012-06-09 05:47:24
【问题描述】:
使用 Jackson 的 WRAP_ROOT_VALUE 序列化设置并序列化 POJO 时,类名用作序列化 JSON 中的根值。
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
问题 - 如何将命名策略应用于类名?我想将类名转换为其他名称。
【问题讨论】:
使用 Jackson 的 WRAP_ROOT_VALUE 序列化设置并序列化 POJO 时,类名用作序列化 JSON 中的根值。
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
问题 - 如何将命名策略应用于类名?我想将类名转换为其他名称。
【问题讨论】:
我的做法是使用@JsonRootName 注释,例如:
@JsonRootName( value = "smsMessageRequest" )
public class TextMessage {
private String message;
private String address;
}
public static String toJson(Object object) throws IOException {
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(JsonMethod.FIELD, Visibility.ANY);
mapper.configure(SerializationConfig.Feature.WRAP_ROOT_VALUE, true);
return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
}
结果:
{
"smsMessageRequest" : {
"message" : "abc",
"address" : "123"
}
}
【讨论】: