我需要以特定方式配置Jackson,我将在下面介绍。
id
id
"_id"
后缀添加到属性名称"_ids"
后缀添加到属性名称@JsonId
,理想情况下使用可选值覆盖名称,就像@JsonProperty
那样@JsonIdentityInfo
id
属性可发现性的注释(例如,对JPA场景有用)考虑这些POJO:
//Inform Jackson which property is the id
@JsonIdentityInfo(
generator = ObjectIdGenerators.PropertyGenerator.class,
property = "id"
)
public abstract class BaseResource{
protected Long id;
//getters and setters
}
public class Resource extends BaseResource{
private String name;
@JsonId
private SubResource subResource;
@JsonId
private List<SubResource> subResources;
//getters and setters
}
public class SubResource extends BaseResource{
private String value;
//getters and setters
}
Resource
实例的可能序列化可能是:
{
"resource":{
"id": 1,
"name": "bla",
"sub_resource_id": 2,
"sub_resource_ids": [
1,
2,
3
]
}
}
要求#5 可以通过以下方式配置ObjectMapper
来完成:
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
然后在我的POJO中使用@JsonRootName("example_root_name_here")
。
要求#6 可以通过以下方式配置ObjectMapper
来完成:
objectMapper.setPropertyNamingStrategy(
PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
正如您所看到的,仍有许多要求需要实现。对于那些想知道我为什么需要这样的配置的人来说,这是因为我正在为ember.js开发一个REST Web服务(更具体地说是Ember Data)。 如果您可以帮助满足任何要求,您将非常感激。
谢谢!
答案 0 :(得分:7)
您的要求中的大部分(全部?)都可以通过使用上下文序列化程序来完成。从ContextualDeserializer for mapping JSON to different types of maps with Jackson和杰克逊的wiki(http://wiki.fasterxml.com/JacksonFeatureContextualHandlers)得到一个答案,我能够得出以下结论。
您需要从@JsonId注释开始,这是指示属性只需要使用Id属性的键。
import com.fasterxml.jackson.annotation.*;
import java.lang.annotation.*;
@Target({ElementType.FIELD, ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotation // important so that it will get included!
public @interface JsonId {
}
接下来是实际的ContextualSerializer,它可以解决繁重的问题。
import com.fasterxml.jackson.databind.ser.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.core.*;
import java.io.*;
public class ContextualJsonIdSerializer
extends JsonSerializer<BaseResource>
implements ContextualSerializer/*<BaseResource>*/
{
private ObjectMapper mapper;
private boolean useJsonId;
public ContextualJsonIdSerializer(ObjectMapper mapper) { this(mapper, false); }
public ContextualJsonIdSerializer(ObjectMapper mapper, boolean useJsonId) {
this.mapper = mapper;
this.useJsonId = useJsonId;
}
@Override
public void serialize(BaseResource br, JsonGenerator jgen, SerializerProvider provider) throws IOException
{
if ( useJsonId ) {
jgen.writeString(br.getId().toString());
} else {
mapper.writeValue(jgen, br);
}
}
@Override
public JsonSerializer<BaseResource> createContextual(SerializerProvider config, BeanProperty property)
throws JsonMappingException
{
// First find annotation used for getter or field:
System.out.println("Finding annotations for "+property);
if ( null == property ) {
return new ContextualJsonIdSerializer(mapper, false);
}
JsonId ann = property.getAnnotation(JsonId.class);
if (ann == null) { // but if missing, default one from class
ann = property.getContextAnnotation(JsonId.class);
}
if (ann == null ) {//|| ann.length() == 0) {
return this;//new ContextualJsonIdSerializer(false);
}
return new ContextualJsonIdSerializer(mapper, true);
}
}
此类查看BaseResource
属性并检查它们以查看是否存在@JsonId
注释。如果是,则仅使用Id属性,否则传入ObjectMapper
用于序列化该值。这很重要,因为如果您尝试使用(基本上)ContextualSerializer
上下文中的映射器,那么您将获得堆栈溢出,因为它最终会反复调用这些方法。
您的资源应该类似于以下内容。我使用@JsonProperty
注释而不是将功能包装在ContextualSerializer
中,因为重新发明轮子似乎很愚蠢。
import java.util.*;
import com.fasterxml.jackson.annotation.*;
public class Resource extends BaseResource{
private String name;
@JsonProperty("sub_resource_id")
@JsonId
private SubResource subResource;
@JsonProperty("sub_resource_ids")
@JsonId
private List<SubResource> subResources;
//getters and setters
public String getName() {return name;}
public void setName(String name) {this.name = name;}
public SubResource getSubResource() {return subResource;}
public void setSubResource(SubResource subResource) {this.subResource = subResource;}
public List<SubResource> getSubResources() {return subResources;}
public void setSubResources(List<SubResource> subResources) {this.subResources = subResources;}
}
最后,执行序列化的方法只会创建一个额外的ObjectMapper
,并在原始ObjectMapper
中注册一个模块。
// Create the original ObjectMapper
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
// Create a clone of the original ObjectMapper
ObjectMapper objectMapper2 = new ObjectMapper();
objectMapper2.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
objectMapper2.configure(SerializationFeature.WRAP_ROOT_VALUE, true);
objectMapper2.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
// Create a module that references the Contextual Serializer
SimpleModule module = new SimpleModule("JsonId", new Version(1, 0, 0, null));
// All references to SubResource should be run through this serializer
module.addSerializer(SubResource.class, new ContextualJsonIdSerializer(objectMapper2));
objectMapper.registerModule(module);
// Now just use the original objectMapper to serialize