com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector Java Examples

The following examples show how to use com.fasterxml.jackson.module.jaxb.JaxbAnnotationIntrospector. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: TestUnwrapping.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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);
    }
 
Example #2
Source File: TestXmlID2.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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...
}
 
Example #3
Source File: TestXmlID2.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #4
Source File: TestJaxbNullProperties.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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)));
}
 
Example #5
Source File: TestJaxbAutoDetect.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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);
}
 
Example #6
Source File: TestJaxbAnnotationIntrospector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
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());
}
 
Example #7
Source File: TestJaxbAnnotationIntrospector.java    From jackson-modules-base with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #8
Source File: CertificateProcessExecutorTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ObjectMapper getObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
	om.setAnnotationIntrospector(jai);
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example #9
Source File: BaseJaxbTest.java    From jackson-modules-base with Apache License 2.0 5 votes vote down vote up
protected MapperBuilder<?,?> getJaxbAndJacksonMapperBuilder()
{
    return JsonMapper.builder()
            .annotationIntrospector(new AnnotationIntrospectorPair(
                    new JaxbAnnotationIntrospector(),
                    new JacksonAnnotationIntrospector()));
}
 
Example #10
Source File: CertificateUnmarshallingTest.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ObjectMapper getObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
	om.setAnnotationIntrospector(jai);
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example #11
Source File: UnmarshallingTester.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ObjectMapper getObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
	om.setAnnotationIntrospector(jai);
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example #12
Source File: JsonUtils.java    From proarc with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #13
Source File: ApiObjectMapper.java    From components with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #14
Source File: ApiObjectMapper.java    From components with Apache License 2.0 5 votes vote down vote up
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());
}
 
Example #15
Source File: Jackson2Parser.java    From typescript-generator with MIT License 5 votes vote down vote up
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);
        }
    }
}
 
Example #16
Source File: MoreoverJsonActivitySerializer.java    From streams with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #17
Source File: ServerUtil.java    From oxAuth with MIT License 5 votes vote down vote up
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;
}
 
Example #18
Source File: Util.java    From oxAuth with MIT License 5 votes vote down vote up
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;
}
 
Example #19
Source File: OkHttpReplicationClient.java    From nifi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #20
Source File: AllureReportUtils.java    From allure1 with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example #21
Source File: AbstractTestValidationExecutor.java    From dss with GNU Lesser General Public License v2.1 5 votes vote down vote up
private static ObjectMapper getObjectMapper() {
	ObjectMapper om = new ObjectMapper();
	JaxbAnnotationIntrospector jai = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
	om.setAnnotationIntrospector(jai);
	om.enable(SerializationFeature.INDENT_OUTPUT);
	return om;
}
 
Example #22
Source File: QueryResponseMessageJsonEncoder.java    From datawave with Apache License 2.0 5 votes vote down vote up
@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);
}
 
Example #23
Source File: Allure1Plugin.java    From allure2 with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #24
Source File: Utility.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #25
Source File: Utility.java    From SNOMED-in-5-minutes with Apache License 2.0 5 votes vote down vote up
/**
 * 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);

}
 
Example #26
Source File: ConfigMain.java    From nifi-minifi with Apache License 2.0 5 votes vote down vote up
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();
    }
}
 
Example #27
Source File: ShopifySdkObjectMapper.java    From shopify-sdk with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example #28
Source File: JacksonContextResolver.java    From datawave with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #29
Source File: BaseJaxbTest.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
protected MapperBuilder<?,?> getJacksonAndJaxbMapperBuilder()
{
    return JsonMapper.builder()
            .annotationIntrospector(new AnnotationIntrospectorPair(new JacksonAnnotationIntrospector(),
                    new JaxbAnnotationIntrospector()));
}
 
Example #30
Source File: BaseJaxbTest.java    From jackson-modules-base with Apache License 2.0 4 votes vote down vote up
protected MapperBuilder<?,?> getJaxbMapperBuilder()
{
    return JsonMapper.builder()
            .annotationIntrospector(new JaxbAnnotationIntrospector());
}