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

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

Introduction

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

Prototype

public ObjectMapper registerModule(Module module) 

Source Link

Document

Method for registering a module that can extend functionality provided by this mapper; for example, by adding providers for custom serializers and deserializers.

Usage

From source file:ijfx.service.overlay.io.OverlaySaver.java

public void save(List<? extends Overlay> overlays, File file) throws IOException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(Overlay.class, new OverlaySerializer());
    mapper.registerModule(module);

    mapper.writeValue(file, overlays);/*ww w  .  j av a  2s  . com*/

}

From source file:java2typescript.jaxrs.DescriptorGeneratorTest.java

@Test
public void testTypescriptGenerate() throws JsonGenerationException, JsonMappingException, IOException {

    ServiceDescriptorGenerator descGen = new ServiceDescriptorGenerator(
            Collections.singletonList(PeopleRestService.class));

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule("custom-mapping");

    mapper.registerModule(module);

    Module tsModule = descGen.generateTypeScript("modName", null);
    tsModule.write(out);/*from   ww w .  j  av  a2  s  .  c  o  m*/
}

From source file:retrofit.JacksonConverterFactoryTest.java

@Before
public void setUp() {
    SimpleModule module = new SimpleModule();
    module.addSerializer(AnInterface.class, new AnInterfaceSerializer());
    module.addDeserializer(AnInterface.class, new AnInterfaceDeserializer());
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(module);
    mapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_SETTERS, false);
    mapper.configure(MapperFeature.AUTO_DETECT_IS_GETTERS, false);
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY));

    Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/"))
            .addConverterFactory(JacksonConverterFactory.create(mapper)).build();
    service = retrofit.create(Service.class);
}

From source file:com.github.helenusdriver.driver.tools.Tool.java

/**
 * Creates all defined Json schemas based on the provided set of class names
 * and options and add the schemas to the specified map. For each class found;
 * the corresponding array element will be nulled. All others are simply
 * skipped.//from w ww  .  jav a 2s.  co m
 *
 * @author paouelle
 *
 * @param  cnames the set of class names to create Json schemas for
 * @param  suffixes the map of provided suffix values
 * @param  matching whether or not to only create schemas for keyspaces that
 *         matches the specified set of suffixes
 * @param  schemas the map where to record the Json schema for the pojo classes
 *         found
 * @throws LinkageError if the linkage fails for one of the specified entity
 *         class
 * @throws ExceptionInInitializerError if the initialization provoked by one
 *         of the specified entity class fails
 * @throws IOException if an I/O error occurs while generating the Json schemas
 */
private static void createJsonSchemasFromClasses(String[] cnames, Map<String, String> suffixes,
        boolean matching, Map<Class<?>, JsonSchema> schemas) throws IOException {
    next_class: for (int i = 0; i < cnames.length; i++) {
        try {
            final Class<?> clazz = Class.forName(cnames[i]);

            cnames[i] = null; // clear since we found a class
            final CreateSchema<?> cs = StatementBuilder.createSchema(clazz);

            // pass all required suffixes
            for (final Map.Entry<String, String> e : suffixes.entrySet()) {
                // check if this suffix type is defined
                final FieldInfo<?> suffix = cs.getClassInfo().getSuffixKeyByType(e.getKey());

                if (suffix != null) {
                    // register the suffix value with the corresponding suffix name
                    cs.where(StatementBuilder.eq(suffix.getSuffixKeyName(), e.getValue()));
                } else if (matching) {
                    // we have one more suffix then defined with this pojo
                    // and we were requested to only do does that match the provided
                    // suffixes so skip the class
                    continue next_class;
                }
            }
            for (final Class<?> c : cs.getObjectClasses()) {
                System.out.println(Tool.class.getSimpleName() + ": creating Json schema for " + c.getName());
                final ObjectMapper m = new ObjectMapper();
                final SchemaFactoryWrapper visitor = new SchemaFactoryWrapper();

                m.registerModule(new Jdk8Module());
                m.enable(SerializationFeature.INDENT_OUTPUT);
                m.acceptJsonFormatVisitor(m.constructType(c), visitor);
                schemas.put(c, visitor.finalSchema());
            }
        } catch (ClassNotFoundException e) { // ignore and continue
        }
    }
}

From source file:architecture.ee.web.community.social.facebook.FacebookServiceProvider.java

@Override
protected ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new FacebookModule());
    return mapper;
}

From source file:org.lightadmin.core.config.context.LightAdminRepositoryRestMvcConfiguration.java

@Override
protected void configureJacksonObjectMapper(ObjectMapper objectMapper) {
    objectMapper.registerModule(new LightAdminJacksonModule(globalAdministrationConfiguration()));
}

From source file:com.basho.riak.client.api.convert.RiakBeanSerializerModifierTest.java

@Test
public void changePropertiesDropsRiakAnnotatedProperties() throws Exception {
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new RiakJacksonModule());

    RiakAnnotatedClass rac = new RiakAnnotatedClass();

    String json = mapper.writeValueAsString(rac);

    @SuppressWarnings("unchecked")
    Map<String, String> map = mapper.readValue(json, Map.class);

    assertEquals(2, map.size());/*from   w  w  w .  jav a2s.c o  m*/
    assertTrue(map.containsKey("someField"));
    assertTrue(map.containsKey("someOtherField"));

    RiakAnnotatedClassWithPublicFields racwpf = new RiakAnnotatedClassWithPublicFields();

    json = mapper.writeValueAsString(racwpf);

    map = mapper.readValue(json, Map.class);

    assertEquals(2, map.size());
    assertTrue(map.containsKey("someField"));
    assertTrue(map.containsKey("someOtherField"));

    // Test the combination of a Riak annotation and the Jackson @JsonProperty
    RiakAnnotatedClassWithJsonProp racwjp = new RiakAnnotatedClassWithJsonProp();
    json = mapper.writeValueAsString(racwjp);

    map = mapper.readValue(json, Map.class);

    assertEquals(4, map.size());
    assertTrue(map.containsKey("keyField"));
    assertTrue(map.containsKey("metaValueField"));
    assertTrue(map.containsKey("someField"));
    assertTrue(map.containsKey("someOtherField"));

}

From source file:edu.ucsd.crbs.cws.dao.rest.WorkflowRestDAOImpl.java

@Override
public Workflow getWorkflowById(String workflowId, User user) throws Exception {
    ClientConfig cc = new DefaultClientConfig();
    cc.getFeatures().put(JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
    Client client = Client.create(cc);/*w ww .ja  v a2  s  .co  m*/
    client.addFilter(new HTTPBasicAuthFilter(user.getLogin(), user.getToken()));
    client.setFollowRedirects(true);
    WebResource resource = client.resource(_restURL).path(Constants.REST_PATH).path(Constants.WORKFLOWS_PATH)
            .path(workflowId);
    MultivaluedMap queryParams = _multivaluedMapFactory.getMultivaluedMap(_user);
    String json = resource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(String.class);
    ObjectMapper mapper = new ObjectMapper();
    mapper.registerModule(new ObjectifyJacksonModule());
    return mapper.readValue(json, new TypeReference<Workflow>() {
    });
}

From source file:org.lable.rfc3881.auditlogger.serialization.ReferenceableSerializerTest.java

@Test
public void nullFieldAlwaysTest() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    objectMapper.registerModule(new ReferenceableSerializerModule());

    CodeReference codeReference = new CodeReference("CS", "", "001", "One", null);

    String result = objectMapper.writeValueAsString(codeReference);

    assertThat(result, is("{" + "\"cs\":\"CS\"," + "\"code\":\"001\"," + "\"csn\":\"\"," + "\"dn\":\"One\","
            + "\"ot\":null" + "}"));
}

From source file:org.lable.rfc3881.auditlogger.serialization.ReferenceableSerializerTest.java

@Test
public void nullFieldTest() throws IOException {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    objectMapper.registerModule(new ReferenceableSerializerModule());

    CodeReference codeReference = new CodeReference("CS", "001", "One");

    String result = objectMapper.writeValueAsString(codeReference);

    assertThat(result, is("{" + "\"cs\":\"CS\"," + "\"code\":\"001\"," + "\"dn\":\"One\"" + "}"));
}