Example usage for com.fasterxml.jackson.databind ObjectMapper setAnnotationIntrospector

List of usage examples for com.fasterxml.jackson.databind ObjectMapper setAnnotationIntrospector

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind ObjectMapper setAnnotationIntrospector.

Prototype

public ObjectMapper setAnnotationIntrospector(AnnotationIntrospector ai) 

Source Link

Document

Method for changing AnnotationIntrospector used by this mapper instance for both serialization and deserialization

Usage

From source file:com.google.api.server.spi.ObjectMapperUtil.java

/**
 * Creates an Endpoints standard object mapper that allows unquoted field names and unknown
 * properties.//  w w  w  . j av a2s .  com
 *
 * Note on unknown properties: When Apiary FE supports a strict mode where properties
 * are checked against the schema, BE can just ignore unknown properties.  This way, FE does
 * not need to filter out everything that the BE doesn't understand.  Before that's done,
 * a property name with a typo in it, for example, will just be ignored by the BE.
 */
public static ObjectMapper createStandardObjectMapper(ApiSerializationConfig config) {
    ObjectMapper objectMapper = new ObjectMapper().configure(JsonParser.Feature.ALLOW_COMMENTS, true)
            .configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true)
            .configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false).setSerializerFactory(
                    BeanSerializerFactory.instance.withSerializerModifier(new DeepEmptyCheckingModifier()));
    AnnotationIntrospector pair = AnnotationIntrospector.pair(new ApiAnnotationIntrospector(config),
            new JacksonAnnotationIntrospector());
    objectMapper.setAnnotationIntrospector(pair);
    return objectMapper;
}

From source file:com.epam.ta.reportportal.core.configs.JacksonConfiguration.java

/**
 * /*from w  ww .  j av  a2  s. c  o  m*/
 * 
 * @return
 */
@Bean(name = "objectMapper")
public ObjectMapper objectMapper() {
    ObjectMapper om = new ObjectMapper();
    om.setAnnotationIntrospector(new JacksonAnnotationIntrospector());
    om.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);
    om.registerModule(new JacksonViewAwareModule(om));
    return om;
}

From source file:org.jbr.taskmgr.config.WebMvcConfig.java

private MappingJackson2HttpMessageConverter createMappingJackson2HttpMessageConverter() {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector());
    converter.setObjectMapper(objectMapper);
    return converter;
}

From source file:org.xwiki.velocity.tools.JSONTool.java

/**
 * Serialize a Java object to the JSON format.
 * <p>//w w w. j a v  a2  s.c o  m
 * Examples:
 * <ul>
 * <li>numbers and boolean values: 23, 13.5, true, false</li>
 * <li>strings: "one\"two'three" (quotes included)</li>
 * <li>arrays and collections: [1, 2, 3]</li>
 * <li>maps: {"number": 23, "boolean": false, "string": "value"}</li>
 * <li>beans: {"enabled": true, "name": "XWiki"} for a bean that has #isEnabled() and #getName() getters</li>
 * </ul>
 *
 * @param object the object to be serialized to the JSON format
 * @return the JSON-verified string representation of the given object
 */
public String serialize(Object object) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setAnnotationIntrospector(CustomAnnotationIntrospector.INTROSPECTOR);
        return mapper.writeValueAsString(object);
    } catch (JsonProcessingException e) {
        this.logger.error("Failed to serialize object to JSON", e);
    }

    return null;
}

From source file:org.axiom_tools.codecs.ModelCodec.java

/**
 * Returns a new JSON object mapper.//w  ww.ja  v a2  s  .  co m
 */
private ObjectMapper buildObjectMapper() {
    ObjectMapper result = new ObjectMapper();
    result.setAnnotationIntrospector(new JaxbAnnotationIntrospector(result.getTypeFactory()));
    result.enable(SerializationFeature.INDENT_OUTPUT);
    return result;
}

From source file:org.apache.nifi.processors.msgpack.MessagePackPack.java

@Override
public void onTrigger(final ProcessContext context, final ProcessSession session) throws ProcessException {
    FlowFile flowFile = session.get();/* w w w  . j  ava2  s .c o m*/
    if (flowFile == null) {
        return;
    }

    final ObjectMapper reader = new ObjectMapper();
    final ObjectMapper writer = new ObjectMapper(new MessagePackFactory());
    writer.setAnnotationIntrospector(new JsonArrayFormat());

    final AtomicBoolean failed = new AtomicBoolean(false);
    flowFile = session.write(flowFile, new StreamCallback() {
        @Override
        public void process(InputStream is, OutputStream os) throws IOException {
            try (final OutputStream msgpack = new BufferedOutputStream(os)) {
                final JsonNode json = reader.readTree(is);
                final byte[] bytes = writer.writeValueAsBytes(json);
                msgpack.write(bytes);
                msgpack.flush();
            } catch (JsonProcessingException e) {
                getLogger().error(e.getMessage(), e);
                failed.set(true);
            }
        }
    });

    if (failed.get()) {
        session.transfer(flowFile, REL_FAILURE);
        return;
    }

    flowFile = session.putAttribute(flowFile, CoreAttributes.MIME_TYPE.key(), MIME_TYPE);
    flowFile = session.putAttribute(flowFile, MIME_EXT_KEY, MIME_EXT);

    session.transfer(flowFile, REL_SUCCESS);
}

From source file:org.apache.streams.data.MoreoverJsonActivitySerializer.java

@Override
public Activity deserialize(String serialized) {
    serialized = serialized.replaceAll("\\[[ ]*\\]", "null");

    System.out.println(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;/* w  w  w . j  a va2  s.c  o m*/
    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 e) {
        throw new IllegalArgumentException("Unable to deserialize", e);
    }
    return MoreoverUtils.convert(article);
}

From source file:org.apache.streams.moreover.MoreoverJsonActivitySerializer.java

@Override
public Activity deserialize(String serialized) {
    serialized = serialized.replaceAll("\\[[ ]*\\]", "null");

    LOGGER.debug(serialized);/* w w w .  jav a 2s.  c  o  m*/

    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);
}

From source file:com.devnexus.ting.core.model.SpeakerJacksonTest.java

@Test
@Ignore//from  ww  w .j a  v  a  2  s . co m
public void testJacksonSerialization() throws JsonGenerationException, JsonMappingException, IOException {

    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
    // make deserializer use JAXB annotations (only)
    mapper.setAnnotationIntrospector(introspector);
    // make serializer use JAXB annotations (only)
    mapper.setAnnotationIntrospector(introspector);

    Speaker speaker = new Speaker();

    speaker.setBio("bio");
    speaker.setFirstName("firstName");
    speaker.setLastName("lastName");

    mapper.writeValue(System.out, speaker);

}

From source file:dk.lnj.swagger4ee.AbstractJSonTest.java

public void makeCompare(SWRoot root, String expFile) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    // make deserializer use JAXB annotations (only)
    mapper.setAnnotationIntrospector(introspector);
    // make serializer use JAXB annotations (only)

    StringWriter sw = new StringWriter();
    mapper.writeValue(sw, root);//from   w w  w .  j  av  a 2 s . c om
    mapper.writeValue(new FileWriter(new File("lasttest.json")), root);

    String actual = sw.toString();
    String expected = new String(Files.readAllBytes(Paths.get(expFile)));

    String[] exp_split = expected.split("\n");
    String[] act_split = actual.split("\n");

    for (int i = 0; i < exp_split.length; i++) {
        String exp = exp_split[i];
        String act = act_split[i];
        String shortFileName = expFile.substring(expFile.lastIndexOf("/"));
        Assert.assertEquals(shortFileName + ":" + (i + 1), superTrim(exp), superTrim(act));
    }

}