下面列出了com.fasterxml.jackson.databind.introspect.AnnotationIntrospectorPair#com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
public void testJaxbAnnotatedObject() throws Exception
{
AnnotationIntrospector primary = new JaxbAnnotationIntrospector();
AnnotationIntrospector secondary = new JacksonAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
ObjectMapper mapper = objectMapperBuilder()
.annotationIntrospector(pair)
.build();
JaxbAnnotatedObject original = new JaxbAnnotatedObject("123");
String json = mapper.writeValueAsString(original);
assertFalse("numberString field in JSON", json.contains("numberString")); // kinda hack-y :)
JaxbAnnotatedObject result = mapper.readValue(json, JaxbAnnotatedObject.class);
assertEquals(new BigDecimal("123"), result.number);
}
public void testRootNameAccess() throws Exception
{
final TypeFactory tf = MAPPER.getTypeFactory();
AnnotationIntrospector ai = new JaxbAnnotationIntrospector();
// If no @XmlRootElement, should get null (unless pkg has etc)
assertNull(ai.findRootName(MAPPER.serializationConfig(),
AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
tf.constructType(SimpleBean.class), null)));
// With @XmlRootElement, but no name, empty String
PropertyName rootName = ai.findRootName(MAPPER.serializationConfig(),
AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
tf.constructType(NamespaceBean.class), null));
assertNotNull(rootName);
assertEquals("", rootName.getSimpleName());
assertEquals("urn:class", rootName.getNamespace());
// and otherwise explicit name
rootName = ai.findRootName(MAPPER.serializationConfig(),
AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
tf.constructType(RootNameBean.class), null));
assertNotNull(rootName);
assertEquals("test", rootName.getSimpleName());
assertNull(rootName.getNamespace());
}
/**
* Additional simple tests to ensure we will retain basic namespace information
* now that it can be included
*/
public void testNamespaces() throws Exception
{
final TypeFactory tf = MAPPER.getTypeFactory();
JaxbAnnotationIntrospector ai = new JaxbAnnotationIntrospector();
AnnotatedClass ac = AnnotatedClassResolver.resolve(MAPPER.serializationConfig(),
tf.constructType(NamespaceBean.class), null);
AnnotatedField af = _findField(ac, "string");
assertNotNull(af);
PropertyName pn = ai.findNameForDeserialization(MAPPER.serializationConfig(), af);
assertNotNull(pn);
// JAXB seems to assert field name instead of giving "use default"...
assertEquals("", pn.getSimpleName());
assertEquals("urn:method", pn.getNamespace());
}
public void testNillability() throws Exception
{
ObjectMapper mapper = getJaxbMapper();
// by default, something not marked as nillable will still be written if null
assertEquals("{\"z\":null}", mapper.writeValueAsString(new NonNillableZ()));
assertEquals("{\"z\":3}", mapper.writeValueAsString(new NonNillableZ(3)));
// but we can change that...
mapper = getJaxbMapperBuilder()
.annotationIntrospector(new JaxbAnnotationIntrospector()
.setNonNillableInclusion(JsonInclude.Include.NON_NULL)
)
.addModule(new JaxbAnnotationModule().setNonNillableInclusion(JsonInclude.Include.NON_NULL))
.build();
assertEquals("{}", mapper.writeValueAsString(new NonNillableZ()));
assertEquals("{\"z\":3}", mapper.writeValueAsString(new NonNillableZ(3)));
}
public void testIdWithJacksonRules() throws Exception
{
String expected = "[{\"id\":11,\"username\":\"11\",\"email\":\"[email protected]\","
+"\"department\":{\"id\":9,\"name\":\"department9\",\"employees\":["
+"11,{\"id\":22,\"username\":\"22\",\"email\":\"[email protected]\","
+"\"department\":9}]}},22,{\"id\":33,\"username\":\"33\",\"email\":\"[email protected]\",\"department\":null}]";
ObjectMapper mapper = JsonMapper.builder()
// true -> ignore XmlIDREF annotation
.annotationIntrospector(new JaxbAnnotationIntrospector(true))
.build();
// first, with default settings (first NOT as id)
List<User> users = getUserList();
String json = mapper.writeValueAsString(users);
assertEquals(expected, json);
List<User> result = mapper.readValue(json, new TypeReference<List<User>>() { });
assertEquals(3, result.size());
assertEquals(Long.valueOf(11), result.get(0).id);
assertEquals(Long.valueOf(22), result.get(1).id);
assertEquals(Long.valueOf(33), result.get(2).id);
}
public void testIdWithJaxbRules() throws Exception
{
ObjectMapper mapper = JsonMapper.builder()
// but then also variant where ID is ALWAYS used for XmlID / XmlIDREF
.annotationIntrospector(new JaxbAnnotationIntrospector())
.build();
List<User> users = getUserList();
final String json = mapper.writeValueAsString(users);
String expected = "[{\"id\":11,\"username\":\"11\",\"email\":\"[email protected]\",\"department\":9}"
+",{\"id\":22,\"username\":\"22\",\"email\":\"[email protected]\",\"department\":9}"
+",{\"id\":33,\"username\":\"33\",\"email\":\"[email protected]\",\"department\":null}]";
assertEquals(expected, json);
// However, there is no way to resolve those back, without some external mechanism...
}
public void testXmlElementAndXmlElementRefs() throws Exception
{
Bean<A> bean = new Bean<A>();
bean.r = new A(12);
bean.name = "test";
AnnotationIntrospector pair = new AnnotationIntrospectorPair(
new JacksonAnnotationIntrospector(),
new JaxbAnnotationIntrospector());
ObjectMapper mapper = objectMapperBuilder()
.annotationIntrospector(pair)
.build();
// mapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector());
// mapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector());
String json = mapper.writeValueAsString(bean);
// !!! TODO: verify
assertNotNull(json);
}
@Override
public void init(EndpointConfig config) {
mapper = new ObjectMapper();
mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(),
new JaxbAnnotationIntrospector(mapper.getTypeFactory())));
// Don't close the output stream
mapper.configure(JsonGenerator.Feature.AUTO_CLOSE_TARGET, false);
// Don't include NULL properties.
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
public JacksonContextResolver() {
mapper = new ObjectMapper();
mapper.enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(new JacksonAnnotationIntrospector(),
new JaxbAnnotationIntrospector(mapper.getTypeFactory())));
mapper.setSerializationInclusion(Include.NON_NULL);
}
public static ObjectMapper buildMapper() {
final ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
final AnnotationIntrospector pair = AnnotationIntrospector.pair(
new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()), new JacksonAnnotationIntrospector());
mapper.setAnnotationIntrospector(pair);
mapper.enable(MapperFeature.USE_ANNOTATIONS);
return mapper;
}
public static ConfigSchema transformVersionedFlowSnapshotToSchema(InputStream source) throws IOException {
try {
final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
objectMapper.setAnnotationIntrospector(new JaxbAnnotationIntrospector(objectMapper.getTypeFactory()));
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
final VersionedFlowSnapshot versionedFlowSnapshot = objectMapper.readValue(source, VersionedFlowSnapshot.class);
return transformVersionedFlowSnapshotToSchema(versionedFlowSnapshot);
} finally {
source.close();
}
}
/**
* Returns the graph for json.
*
* @param <T> the generic type
* @param json the json
* @param graphClass the graph class
* @return the graph for json
* @throws Exception the exception
*/
public static <T> T getGraphForJson(String json, Class<T> graphClass)
throws Exception {
InputStream in =
new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8));
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector =
new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector);
return mapper.readValue(in, graphClass);
}
/**
* Returns the json for graph.
*
* @param object the object
* @return the json for graph
* @throws Exception the exception
*/
public static String getJsonForGraph(Object object) throws Exception {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector =
new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector);
return mapper.writeValueAsString(object);
}
public Allure1Plugin() {
final SimpleModule module = new XmlParserModule()
.addDeserializer(ru.yandex.qatools.allure.model.Status.class, new StatusDeserializer());
xmlMapper = new XmlMapper()
.configure(USE_WRAPPER_NAME_AS_PROPERTY_NAME, true)
.setAnnotationIntrospector(new JaxbAnnotationIntrospector(TypeFactory.defaultInstance()))
.registerModule(module);
}
protected MapperBuilder<?,?> getJaxbAndJacksonMapperBuilder()
{
return JsonMapper.builder()
.annotationIntrospector(new AnnotationIntrospectorPair(
new JaxbAnnotationIntrospector(),
new JacksonAnnotationIntrospector()));
}
private static ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
om.setAnnotationIntrospector(jai);
om.enable(SerializationFeature.INDENT_OUTPUT);
return om;
}
private static ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
om.setAnnotationIntrospector(jai);
om.enable(SerializationFeature.INDENT_OUTPUT);
return om;
}
private static ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
om.setAnnotationIntrospector(jai);
om.enable(SerializationFeature.INDENT_OUTPUT);
return om;
}
private static ObjectMapper getObjectMapper() {
ObjectMapper om = new ObjectMapper();
JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
om.setAnnotationIntrospector(jai);
om.enable(SerializationFeature.INDENT_OUTPUT);
return om;
}
/**
* Creates a configured mapper supporting JAXB.
* @see #createObjectMapper(com.fasterxml.jackson.databind.ObjectMapper)
*/
public static ObjectMapper createJaxbMapper() {
ObjectMapper om = createObjectMapper(createObjectMapper());
JaxbAnnotationIntrospector jaxbIntr = new JaxbAnnotationIntrospector(om.getTypeFactory());
JacksonAnnotationIntrospector jsonIntr = new JacksonAnnotationIntrospector();
om.setAnnotationIntrospector(new AnnotationIntrospectorPair(jsonIntr, jaxbIntr));
return om;
}
public ApiObjectMapper() {
// Print the JSON with indentation (ie. pretty print)
configure(SerializationFeature.INDENT_OUTPUT, true);
// Allow JAX-B annotations.
setAnnotationIntrospector(AnnotationIntrospector.pair(getSerializationConfig().getAnnotationIntrospector(),
new JaxbAnnotationIntrospector()));
// Make Jackson respect @XmlElementWrapper.
enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
// Print all dates in ISO8601 format
setDateFormat(makeISODateFormat());
}
public ApiObjectMapper() {
// Print the JSON with indentation (ie. pretty print)
configure(SerializationFeature.INDENT_OUTPUT, true);
// Allow JAX-B annotations.
setAnnotationIntrospector(AnnotationIntrospector.pair(getSerializationConfig().getAnnotationIntrospector(),
new JaxbAnnotationIntrospector()));
// Make Jackson respect @XmlElementWrapper.
enable(MapperFeature.USE_WRAPPER_NAME_AS_PROPERTY_NAME);
// Print all dates in ISO8601 format
setDateFormat(makeISODateFormat());
}
public Jackson2Parser(Settings settings, TypeProcessor commonTypeProcessor, List<RestApplicationParser> restApplicationParsers, boolean useJaxbAnnotations) {
super(settings, commonTypeProcessor, restApplicationParsers);
if (settings.jackson2ModuleDiscovery) {
objectMapper.registerModules(ObjectMapper.findModules(settings.classLoader));
}
for (Class<? extends Module> moduleClass : settings.jackson2Modules) {
try {
objectMapper.registerModule(moduleClass.getConstructor().newInstance());
} catch (ReflectiveOperationException e) {
throw new RuntimeException(String.format("Cannot instantiate Jackson2 module '%s'", moduleClass.getName()), e);
}
}
if (useJaxbAnnotations) {
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(objectMapper.getTypeFactory());
objectMapper.setAnnotationIntrospector(introspector);
}
final Jackson2ConfigurationResolved config = settings.jackson2Configuration;
if (config != null) {
setVisibility(PropertyAccessor.FIELD, config.fieldVisibility);
setVisibility(PropertyAccessor.GETTER, config.getterVisibility);
setVisibility(PropertyAccessor.IS_GETTER, config.isGetterVisibility);
setVisibility(PropertyAccessor.SETTER, config.setterVisibility);
setVisibility(PropertyAccessor.CREATOR, config.creatorVisibility);
if (config.shapeConfigOverrides != null) {
config.shapeConfigOverrides.entrySet()
.forEach(entry -> setShapeOverride(entry.getKey(), entry.getValue()));
}
if (config.enumsUsingToString) {
objectMapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
objectMapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
}
}
}
@Override
public Activity deserialize(String serialized) {
serialized = serialized.replaceAll("\\[[ ]*\\]", "null");
LOGGER.debug(serialized);
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
mapper.setAnnotationIntrospector(introspector);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, Boolean.FALSE);
mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, Boolean.FALSE);
mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, Boolean.TRUE);
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, Boolean.TRUE);
mapper.configure(DeserializationFeature.WRAP_EXCEPTIONS, Boolean.TRUE);
Article article;
try {
ObjectNode node = (ObjectNode)mapper.readTree(serialized);
node.remove("tags");
node.remove("locations");
node.remove("companies");
node.remove("topics");
node.remove("media");
node.remove("outboundUrls");
ObjectNode jsonNodes = (ObjectNode) node.get("source").get("feed");
jsonNodes.remove("editorialTopics");
jsonNodes.remove("tags");
jsonNodes.remove("autoTopics");
article = mapper.convertValue(node, Article.class);
} catch (IOException ex) {
throw new IllegalArgumentException("Unable to deserialize", ex);
}
return MoreoverUtils.convert(article);
}
public static ObjectMapper createJsonMapper() {
final AnnotationIntrospector jaxb = new JaxbAnnotationIntrospector();
final AnnotationIntrospector jackson = new JacksonAnnotationIntrospector();
final AnnotationIntrospector pair = AnnotationIntrospector.pair(jackson, jaxb);
final ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().with(pair);
mapper.getSerializationConfig().with(pair);
return mapper;
}
public static ObjectMapper createJsonMapper() {
final AnnotationIntrospector jaxb = new JaxbAnnotationIntrospector();
final AnnotationIntrospector jackson = new JacksonAnnotationIntrospector();
final AnnotationIntrospector pair = AnnotationIntrospector.pair(jackson, jaxb);
final ObjectMapper mapper = new ObjectMapper();
mapper.getDeserializationConfig().with(pair);
mapper.getSerializationConfig().with(pair);
return mapper;
}
public OkHttpReplicationClient(final NiFiProperties properties) {
jsonCodec.setDefaultPropertyInclusion(Value.construct(Include.NON_NULL, Include.ALWAYS));
jsonCodec.setAnnotationIntrospector(new JaxbAnnotationIntrospector(jsonCodec.getTypeFactory()));
jsonSerializer = new JsonEntitySerializer(jsonCodec);
xmlSerializer = new XmlEntitySerializer();
okHttpClient = createOkHttpClient(properties);
}
/**
* Create Jackson mapper with {@link JaxbAnnotationIntrospector}
*
* @return {@link com.fasterxml.jackson.databind.ObjectMapper}
*/
public static ObjectMapper createMapperWithJaxbAnnotationInspector() {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector annotationInspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.getSerializationConfig().with(annotationInspector);
return mapper;
}
public void testVersions()
{
assertVersion(new JaxbAnnotationIntrospector());
}
protected MapperBuilder<?,?> getJaxbMapperBuilder()
{
return JsonMapper.builder()
.annotationIntrospector(new JaxbAnnotationIntrospector());
}