我使用下面的代碼從link爲我的數據模型類(JSON到JAXB模型轉換)添加自定義反序列化器。JacksonJaxbJsonProvider默認的objectmapper映射
我想使用com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider
爲我的JSON序列化/反序列化其他數據模型。
JacksonJaxbJsonProvider
的默認實現對於具有超類作爲抽象類的JAXB模型非常適用。但是,一旦我提供了自己的自定義ObjectMapper(如下所示),則不會使用JacksonJaxbJsonProvider
的默認實現。即爲我的抽象類聲明的JAXB註釋和字段未由Custom ObjectMapper正確轉換,因爲它無法找到抽象類中聲明的字段。
所以我想同時使用自定義ObjectMapper和默認實現JacksonJaxbJsonProvider
,這取決於所討論的JAXB模型。
40 package org.glassfish.jersey.examples.jackson;
41
42 import javax.ws.rs.ext.ContextResolver;
43 import javax.ws.rs.ext.Provider;
44
45 import com.fasterxml.jackson.databind.AnnotationIntrospector;
46 import com.fasterxml.jackson.databind.DeserializationFeature;
47 import com.fasterxml.jackson.databind.ObjectMapper;
48 import com.fasterxml.jackson.databind.SerializationFeature;
49 import com.fasterxml.jackson.databind.introspect.JacksonAnnotationIntrospector;
50 import com.fasterxml.jackson.databind.type.TypeFactory;
51 import com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector;
52
53 /**
54 * TODO javadoc.
55 *
56 * @author Jakub Podlesak (jakub.podlesak at oracle.com)
57 */
58 @Provider
59 public class MyObjectMapperProvider implements ContextResolver<ObjectMapper> {
60
61 final ObjectMapper defaultObjectMapper;
62 final ObjectMapper combinedObjectMapper;
63
64 public MyObjectMapperProvider() {
65 defaultObjectMapper = createDefaultMapper();
66 combinedObjectMapper = createCombinedObjectMapper();
67 }
68
69 @Override
70 public ObjectMapper getContext(final Class<?> type) {
71
72 if (type == CombinedAnnotationBean.class) {
73 return combinedObjectMapper;
74 } else {
75 return defaultObjectMapper;
76 }
77 }
78
79 private static ObjectMapper createCombinedObjectMapper() {
80 return new ObjectMapper()
81 .configure(SerializationFeature.WRAP_ROOT_VALUE, true)
82 .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true)
83 .setAnnotationIntrospector(createJaxbJacksonAnnotationIntrospector());
84 }
85
86 private static ObjectMapper createDefaultMapper() {
87 final ObjectMapper result = new ObjectMapper();
88 result.enable(SerializationFeature.INDENT_OUTPUT);
89
90 return result;
91 }
92
93 private static AnnotationIntrospector createJaxbJacksonAnnotationIntrospector() {
94
95 final AnnotationIntrospector jaxbIntrospector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
96 final AnnotationIntrospector jacksonIntrospector = new JacksonAnnotationIntrospector();
97
98 return AnnotationIntrospector.pair(jacksonIntrospector, jaxbIntrospector);
99 }
100 }
你有這個過程困惑。 ObjectMapper不使用提供者。提供者使用映射器。話雖如此,你的問題並不完全合理。也許語法讓我感到困惑。你可以嘗試重新提出這個問題。很多嘗試清理第三段。這是有點不清楚你到底想完成什麼,以及爲什麼你提供的代碼不適合你 –
@Meiko你鏈接到這個相同的問題 –
@peeskillet :-D哦,是的......昨天太遲了..這一個:http://stackoverflow.com/questions/18872931/custom-objectmapper-with-jersey-2-2-and-jackson-2-1 –