Example usage for com.fasterxml.jackson.databind.module SimpleModule SimpleModule

List of usage examples for com.fasterxml.jackson.databind.module SimpleModule SimpleModule

Introduction

In this page you can find the example usage for com.fasterxml.jackson.databind.module SimpleModule SimpleModule.

Prototype

public SimpleModule(String name, Version version) 

Source Link

Document

Constructor to use for actual reusable modules.

Usage

From source file:net.solarnetwork.util.ObjectMapperFactoryBean.java

@Override
public ObjectMapper getObject() throws Exception {
    if (mapper == null) {
        mapper = new ObjectMapper();
    }/*from  w  w  w  .j a  v  a 2 s . c  o  m*/
    SimpleModule module = new SimpleModule(moduleName, moduleVersion);
    if (serializers != null) {
        for (JsonSerializer<?> serializer : serializers) {
            module.addSerializer(serializer);
        }
    }
    if (deserializers != null) {
        for (JsonDeserializer<?> deserializer : deserializers) {
            if (deserializer instanceof StdDeserializer<?>) {
                registerStdDeserializer(module, (StdDeserializer<?>) deserializer);
            }
        }
    }
    if (serializationInclusion != null) {
        mapper.setSerializationInclusion(serializationInclusion);
    }
    setupFeatures(mapper, featuresToEnable, true);
    setupFeatures(mapper, featuresToDisable, false);
    mapper.registerModule(module);
    return mapper;
}

From source file:com.groupdocs.sdk.common.ApiInvoker.java

@SuppressWarnings("unchecked")
public static Object deserialize(String json, String containerType, @SuppressWarnings("rawtypes") Class cls)
        throws ApiException {
    try {//from  w w  w . j a v  a2s.  c om
        ObjectMapper mapper = JsonUtil.getJsonMapper();
        SimpleModule m = new SimpleModule(PACKAGE_NAME, Version.unknownVersion());
        m.addDeserializer(Date.class, new CustomDateDeserializer(new DateDeserializer()));
        mapper.registerModule(m);

        if ("List".equals(containerType)) {
            JavaType typeInfo = mapper.getTypeFactory().constructCollectionType(List.class, cls);
            List<?> response = (List<?>) mapper.readValue(json, typeInfo);
            return response;
        } else if (String.class.equals(cls)) {
            return json;
        } else {
            return mapper.readValue(json, cls);
        }
    } catch (IOException e) {
        throw new ApiException(500, e.getMessage());
    }
}

From source file:com.basho.riak.client.api.commands.mapreduce.MapReduce.java

/**
 * Creates the JSON string of the M/R job for submitting to the client
 * <p/>/*from  ww w .j a v a 2  s. c  o m*/
 * Uses Jackson to write out the JSON string. I'm not very happy with this method, it is a candidate for change.
 * <p/>
 * TODO re-evaluate this method, look for something smaller and more elegant.
 *
 * @return a String of JSON
 * @throws RiakException if, for some reason, we can't create a JSON string.
 */
String writeSpec() throws RiakException {

    final ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {
        JsonGenerator jg = new JsonFactory().createGenerator(out, JsonEncoding.UTF8);

        ObjectMapper objectMapper = new ObjectMapper();
        SimpleModule specModule = new SimpleModule("SpecModule", Version.unknownVersion());
        specModule.addSerializer(LinkPhase.class, new LinkPhaseSerializer());
        specModule.addSerializer(FunctionPhase.class, new FunctionPhaseSerializer());
        specModule.addSerializer(BucketInput.class, new BucketInputSerializer());
        specModule.addSerializer(SearchInput.class, new SearchInputSerializer());
        specModule.addSerializer(BucketKeyInput.class, new BucketKeyInputSerializer());
        specModule.addSerializer(IndexInput.class, new IndexInputSerializer());
        objectMapper.registerModule(specModule);

        jg.setCodec(objectMapper);

        List<MapReducePhase> phases = spec.getPhases();
        phases.get(phases.size() - 1).setKeep(true);
        jg.writeObject(spec);

        jg.flush();

        return out.toString("UTF8");

    } catch (IOException e) {
        throw new RiakException(e);
    }
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriter.java

private static SimpleModule getWriteLongAsStringModule() {
    JsonSerializer<Long> longSerializer = new JsonSerializer<Long>() {
        @Override/*from   w  ww . j  a  va  2 s.c om*/
        public void serialize(Long value, JsonGenerator jgen, SerializerProvider provider) throws IOException {
            jgen.writeString(value.toString());
        }
    };
    SimpleModule writeLongAsStringModule = new SimpleModule("writeLongAsStringModule",
            new Version(1, 0, 0, null, null, null));
    writeLongAsStringModule.addSerializer(Long.TYPE, longSerializer); // long (primitive)
    writeLongAsStringModule.addSerializer(Long.class, longSerializer); // Long (class)
    return writeLongAsStringModule;
}

From source file:com.bazaarvoice.jolt.jsonUtil.testdomain.two.MappingTest2.java

@Test
public void testPolymorphicJacksonSerializationAndDeserialization() {
    ObjectMapper mapper = new ObjectMapper();

    SimpleModule testModule = new SimpleModule("testModule", new Version(1, 0, 0, null, null, null))
            .addDeserializer(QueryFilter.class, new QueryFilterDeserializer())
            .addSerializer(LogicalFilter2.class, new LogicalFilter2Serializer());

    mapper.registerModule(testModule);// www . j  a va 2  s. com

    // Verifying that we can pass in a custom Mapper and create a new JsonUtil
    JsonUtil jsonUtil = JsonUtils.customJsonUtil(mapper);

    String testFixture = "/jsonUtils/testdomain/two/queryFilter-realAndLogical2.json";

    // TEST JsonUtil and our deserialization logic
    QueryFilter queryFilter = jsonUtil.classpathToType(testFixture, new TypeReference<QueryFilter>() {
    });

    // Make sure the hydrated QFilter looks right
    AssertJUnit.assertTrue(queryFilter instanceof LogicalFilter2);
    AssertJUnit.assertEquals(QueryParam.AND, queryFilter.getQueryParam());
    AssertJUnit.assertTrue(queryFilter.isLogical());
    AssertJUnit.assertEquals(3, queryFilter.getFilters().size());
    AssertJUnit.assertNotNull(queryFilter.getFilters().get(QueryParam.OR));

    // Make sure one of the top level RealFilters looks right
    QueryFilter productIdFilter = queryFilter.getFilters().get(QueryParam.PRODUCTID);
    AssertJUnit.assertTrue(productIdFilter.isReal());
    AssertJUnit.assertEquals(QueryParam.PRODUCTID, productIdFilter.getQueryParam());
    AssertJUnit.assertEquals("Acme-1234", productIdFilter.getValue());

    // Make sure the nested OR looks right
    QueryFilter orFilter = queryFilter.getFilters().get(QueryParam.OR);
    AssertJUnit.assertTrue(orFilter.isLogical());
    AssertJUnit.assertEquals(QueryParam.OR, orFilter.getQueryParam());
    AssertJUnit.assertEquals(2, orFilter.getFilters().size());

    // Make sure nested AND looks right
    QueryFilter nestedAndFilter = orFilter.getFilters().get(QueryParam.AND);
    AssertJUnit.assertTrue(nestedAndFilter.isLogical());
    AssertJUnit.assertEquals(QueryParam.AND, nestedAndFilter.getQueryParam());
    AssertJUnit.assertEquals(2, nestedAndFilter.getFilters().size());

    // SERIALIZE TO STRING to test serialization logic
    String unitTestString = jsonUtil.toJsonString(queryFilter);

    // LOAD and Diffy the plain vanilla JSON versions of the documents
    Map<String, Object> actual = JsonUtils.jsonToMap(unitTestString);
    Map<String, Object> expected = JsonUtils.classpathToMap(testFixture);

    // Diffy the vanilla versions
    Diffy.Result result = diffy.diff(expected, actual);
    if (!result.isEmpty()) {
        AssertJUnit.fail("Failed.\nhere is a diff:\nexpected: " + JsonUtils.toJsonString(result.expected)
                + "\n  actual: " + JsonUtils.toJsonString(result.actual));
    }
}

From source file:io.airlift.json.ObjectMapperProvider.java

@Override
public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper();

    // ignore unknown fields (for backwards compatibility)
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    // use ISO dates
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // skip fields that are null instead of writing an explicit json null value
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // disable auto detection of json properties... all properties must be explicit
    objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_FIELDS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_SETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_IS_GETTERS);
    objectMapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
    objectMapper.disable(MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);

    if (jsonSerializers != null || jsonDeserializers != null || keySerializers != null
            || keyDeserializers != null) {
        SimpleModule module = new SimpleModule(getClass().getName(), new Version(1, 0, 0, null));
        if (jsonSerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : jsonSerializers.entrySet()) {
                addSerializer(module, entry.getKey(), entry.getValue());
            }/*from w w  w.jav  a 2s  .c om*/
        }
        if (jsonDeserializers != null) {
            for (Entry<Class<?>, JsonDeserializer<?>> entry : jsonDeserializers.entrySet()) {
                addDeserializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keySerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : keySerializers.entrySet()) {
                addKeySerializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keyDeserializers != null) {
            for (Entry<Class<?>, KeyDeserializer> entry : keyDeserializers.entrySet()) {
                module.addKeyDeserializer(entry.getKey(), entry.getValue());
            }
        }
        modules.add(module);
    }

    for (Module module : modules) {
        objectMapper.registerModule(module);
    }

    return objectMapper;
}

From source file:com.proofpoint.json.ObjectMapperProvider.java

@Override
public ObjectMapper get() {
    ObjectMapper objectMapper = new ObjectMapper();

    // ignore unknown fields (for backwards compatibility)
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

    // use ISO dates
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // skip fields that are null instead of writing an explicit json null value
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // disable auto detection of json properties... all properties must be explicit
    objectMapper.disable(MapperFeature.AUTO_DETECT_CREATORS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_FIELDS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_SETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_GETTERS);
    objectMapper.disable(MapperFeature.AUTO_DETECT_IS_GETTERS);
    objectMapper.disable(MapperFeature.USE_GETTERS_AS_SETTERS);
    objectMapper.disable(MapperFeature.INFER_PROPERTY_MUTATORS);
    objectMapper.disable(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS);

    if (jsonSerializers != null || jsonDeserializers != null || keySerializers != null
            || keyDeserializers != null) {
        SimpleModule module = new SimpleModule(getClass().getName(), new Version(1, 0, 0, null, null, null));
        if (jsonSerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : jsonSerializers.entrySet()) {
                addSerializer(module, entry.getKey(), entry.getValue());
            }//from ww w.ja  v a2s .  c o m
        }
        if (jsonDeserializers != null) {
            for (Entry<Class<?>, JsonDeserializer<?>> entry : jsonDeserializers.entrySet()) {
                addDeserializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keySerializers != null) {
            for (Entry<Class<?>, JsonSerializer<?>> entry : keySerializers.entrySet()) {
                addKeySerializer(module, entry.getKey(), entry.getValue());
            }
        }
        if (keyDeserializers != null) {
            for (Entry<Class<?>, KeyDeserializer> entry : keyDeserializers.entrySet()) {
                module.addKeyDeserializer(entry.getKey(), entry.getValue());
            }
        }
        modules.add(module);
    }

    for (Module module : modules) {
        objectMapper.registerModule(module);
    }

    return objectMapper;
}

From source file:org.elasticsoftware.elasticactors.base.serialization.ObjectMapperBuilder.java

public final ObjectMapper build() {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);

    // scan everything for META-INF/elasticactors.properties
    Set<String> basePackages = new HashSet<>();
    try {/*from  www .  java 2  s . c om*/
        Enumeration<URL> resources = Thread.currentThread().getContextClassLoader().getResources(RESOURCE_NAME);
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            Properties props = new Properties();
            props.load(url.openStream());
            basePackages.add(props.getProperty("basePackage"));
        }
    } catch (IOException e) {
        logger.warn(String.format("Failed to load elasticactors.properties"), e);
    }

    // add other base packages
    if (this.basePackages != null && !"".equals(this.basePackages)) {
        String[] otherPackages = this.basePackages.split(",");
        basePackages.addAll(Arrays.asList(otherPackages));
    }

    ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

    for (String basePackage : basePackages) {
        configurationBuilder.addUrls(ClasspathHelper.forPackage(basePackage));
    }

    Reflections reflections = new Reflections(configurationBuilder);
    registerSubtypes(reflections, objectMapper);

    SimpleModule jacksonModule = new SimpleModule("org.elasticsoftware.elasticactors",
            new Version(1, 0, 0, null, null, null));

    registerCustomSerializers(reflections, jacksonModule);
    registerCustomDeserializers(reflections, jacksonModule);

    objectMapper.registerModule(jacksonModule);

    if (useAfterBurner) {
        // register the afterburner module to increase performance
        // afterburner does NOT work correctly with jackson version lower than 2.4.5! (if @JsonSerialize annotation is used)
        AfterburnerModule afterburnerModule = new AfterburnerModule();
        //afterburnerModule.setUseValueClassLoader(false);
        //afterburnerModule.setUseOptimizedBeanDeserializer(false);
        objectMapper.registerModule(afterburnerModule);
    }

    return objectMapper;
}

From source file:org.osiam.client.AbstractOsiamService.java

protected AbstractOsiamService(Builder<T> builder) {
    type = builder.type;//from ww w.  ja v a 2 s  .  co  m
    typeName = builder.typeName;
    endpoint = builder.endpoint;

    mapper = new ObjectMapper();
    SimpleModule userDeserializerModule = new SimpleModule("userDeserializerModule", Version.unknownVersion())
            .addDeserializer(User.class, new UserDeserializer(User.class));
    mapper.registerModule(userDeserializerModule);

    targetEndpoint = client.target(endpoint);
}

From source file:com.google.api.server.spi.response.ServletResponseResultWriter.java

private static SimpleModule getWriteDateAndTimeAsStringModule() {
    JsonSerializer<DateAndTime> dateAndTimeSerializer = new JsonSerializer<DateAndTime>() {
        @Override//from  ww w.j  a  v a2s  .  c  o  m
        public void serialize(DateAndTime value, JsonGenerator jgen, SerializerProvider provider)
                throws IOException {
            jgen.writeString(value.toRfc3339String());
        }
    };
    SimpleModule writeDateAsStringModule = new SimpleModule("writeDateAsStringModule",
            new Version(1, 0, 0, null, null, null));
    writeDateAsStringModule.addSerializer(DateAndTime.class, dateAndTimeSerializer);
    return writeDateAsStringModule;
}