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() 

Source Link

Document

Constructors that should only be used for non-reusable convenience modules used by app code: "real" modules should use actual name and version number information.

Usage

From source file:org.springframework.data.rest.webmvc.json.PersistentEntityJackson2ModuleUnitTests.java

@Before
public void setUp() {

    KeyValueMappingContext mappingContext = new KeyValueMappingContext();
    mappingContext.getPersistentEntity(Sample.class);
    mappingContext.getPersistentEntity(SampleWithAdditionalGetters.class);
    mappingContext.getPersistentEntity(PersistentEntityJackson2ModuleUnitTests.PetOwner.class);

    this.persistentEntities = new PersistentEntities(Arrays.asList(mappingContext));

    ResourceProcessorInvoker invoker = new ResourceProcessorInvoker(
            Collections.<ResourceProcessor<?>>emptyList());

    NestedEntitySerializer nestedEntitySerializer = new NestedEntitySerializer(persistentEntities,
            new EmbeddedResourcesAssembler(persistentEntities, associations, mock(ExcerptProjector.class)),
            invoker);/*ww w.j  av a  2 s.  com*/
    OrderAwarePluginRegistry<EntityLookup<?>, Class<?>> lookups = OrderAwarePluginRegistry.create();

    SimpleModule module = new SimpleModule();

    module.setSerializerModifier(new AssociationOmittingSerializerModifier(persistentEntities, associations,
            nestedEntitySerializer, new LookupObjectSerializer(lookups)));
    module.setDeserializerModifier(new AssociationUriResolvingDeserializerModifier(persistentEntities,
            associations, converter, mock(RepositoryInvokerFactory.class)));

    this.mapper = new ObjectMapper();
    this.mapper.registerModule(module);
}

From source file:com.google.gplus.processor.GooglePlusTypeConverter.java

@Override
public void prepare(Object configurationObject) {
    googlePlusActivityUtil = new GooglePlusActivityUtil();
    mapper = StreamsJacksonMapper.getInstance();

    SimpleModule simpleModule = new SimpleModule();
    simpleModule.addDeserializer(Person.class, new GPlusPersonDeserializer());
    mapper.registerModule(simpleModule);

    simpleModule = new SimpleModule();
    simpleModule.addDeserializer(com.google.api.services.plus.model.Activity.class,
            new GPlusActivityDeserializer());
    mapper.registerModule(simpleModule);
}

From source file:org.dhatim.dropwizard.jwt.cookie.authentication.JwtCookieAuthBundle.java

@Override
public void initialize(Bootstrap<?> bootstrap) {
    //in case somebody needs to serialize a DefaultJwtCookiePrincipal
    bootstrap.getObjectMapper()// ww w . j a  va2  s  . c o m
            .registerModule(new SimpleModule().addAbstractTypeMapping(Claims.class, DefaultClaims.class));
}

From source file:de.fraunhofer.iosb.ilt.sta.deserialize.EntityParser.java

public EntityParser(Class<? extends Id> idClass) {
    CustomDeserializationManager.getInstance().registerDeserializer("application/vnd.geo+json",
            new GeoJsonDeserializier());
    mapper = new ObjectMapper().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS);
    //mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.setPropertyNamingStrategy(new EntitySetCamelCaseNamingStrategy());
    mapper.addMixIn(Datastream.class, DatastreamMixIn.class);
    mapper.addMixIn(MultiDatastream.class, MultiDatastreamMixIn.class);
    mapper.addMixIn(FeatureOfInterest.class, FeatureOfInterestMixIn.class);
    mapper.addMixIn(HistoricalLocation.class, HistoricalLocationMixIn.class);
    mapper.addMixIn(Location.class, LocationMixIn.class);
    mapper.addMixIn(Observation.class, ObservationMixIn.class);
    mapper.addMixIn(ObservedProperty.class, ObservedPropertyMixIn.class);
    mapper.addMixIn(Sensor.class, SensorMixIn.class);
    mapper.addMixIn(Thing.class, ThingMixIn.class);
    mapper.addMixIn(UnitOfMeasurement.class, UnitOfMeasurementMixIn.class);
    SimpleModule module = new SimpleModule();
    module.addAbstractTypeMapping(EntitySet.class, EntitySetImpl.class);
    module.addAbstractTypeMapping(Id.class, idClass);
    module.addDeserializer(Location.class, new CustomEntityDeserializer(Location.class));
    module.addDeserializer(FeatureOfInterest.class, new CustomEntityDeserializer(FeatureOfInterest.class));
    module.addDeserializer(Sensor.class, new CustomEntityDeserializer(Sensor.class));
    // TODO Datastream.observationType supplies encodingType for Observation.result. How to deserialize content when ne Observation is inserted?
    //module.addDeserializer(Datastream.class, new CustomEntityDeserializer(Datastream.class));
    mapper.registerModule(module);/*  w ww.  ja v  a  2  s. c om*/
}

From source file:io.qdb.server.controller.JsonService.java

private ObjectMapper createMapper(boolean prettyPrint, boolean datesAsTimestamps, boolean borg) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.configure(SerializationFeature.WRITE_NULL_MAP_VALUES, false);
    mapper.configure(SerializationFeature.INDENT_OUTPUT, prettyPrint);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, datesAsTimestamps);

    SimpleModule module = new SimpleModule();
    module.addDeserializer(Date.class, dateDeserializer);
    module.addDeserializer(Integer.class, integerJsonDeserializer);
    module.addDeserializer(Integer.TYPE, integerJsonDeserializer);
    module.addDeserializer(Long.class, longJsonDeserializer);
    module.addDeserializer(Long.TYPE, longJsonDeserializer);
    if (!borg) {//from  w w  w  .jav a2s . co m
        module.addSerializer(Integer.TYPE, integerSerializer);
        module.addSerializer(Integer.class, integerSerializer);
        module.addSerializer(Long.TYPE, longSerializer);
        module.addSerializer(Long.class, longSerializer);
    }
    if (!datesAsTimestamps)
        module.addSerializer(Date.class, new ISO8601DateSerializer());
    mapper.registerModule(module);

    return mapper;
}

From source file:com.hurence.logisland.serializer.JsonSerializer.java

@Override
public void serialize(OutputStream out, Record record) throws RecordSerializationException {

    ObjectMapper mapper = new ObjectMapper();
    SimpleModule module = new SimpleModule();
    module.addSerializer(StandardRecord.class, new EventSerializer());
    mapper.registerModule(module);/* ww  w  .  j a  v a  2s. co  m*/

    //map json to student

    try {
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
        String jsonString = mapper.writeValueAsString(record);

        out.write(jsonString.getBytes());
        out.flush();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

From source file:com.heliosapm.tsdblite.json.JSON.java

/**
 * Registers a ser for the passed class/*from   w  w  w. j  av a  2s. c om*/
 * @param clazz The class for which a ser is being registered
 * @param ser The serializer
 */
public static <T> void registerSerializer(final Class<T> clazz, final JsonSerializer<T> ser) {
    if (clazz == null)
        throw new IllegalArgumentException("The passed class was null");
    if (ser == null)
        throw new IllegalArgumentException("The passed serializer for [" + clazz.getName() + "] was null");
    final SimpleModule module = new SimpleModule();
    module.addSerializer(clazz, ser);
    jsonMapper.registerModule(module);
}

From source file:org.zalando.jackson.datatype.money.MonetaryAmountDeserializerTest.java

@Test
public void defaultConstructorShouldFallbackToMoney() throws IOException {
    final ObjectMapper unit = new ObjectMapper().registerModule(
            new SimpleModule().addDeserializer(CurrencyUnit.class, new CurrencyUnitDeserializer())
                    .addDeserializer(MonetaryAmount.class, new MonetaryAmountDeserializer()));

    final String content = "{\"amount\":29.95,\"currency\":\"EUR\"}";
    final MonetaryAmount amount = unit.readValue(content, MonetaryAmount.class);

    assertThat(amount, is(instanceOf(Money.class)));
}

From source file:nl.knaw.huygens.timbuctoo.rest.providers.HTMLProviderHelper.java

/**
 * Returns an object writer for a class with the specified annotations.
 * <ul>/*from  w w  w.  j  a  va2s.com*/
 * <li>The current implementation is not thread safe.</li>
 * <li>Apparently uses undocumented features of Jackson. In version 2.1 it used
 * <code>com.fasterxml.jackson.jaxrs.json.util.AnnotationBundleKey</code> and
 * <code>com.fasterxml.jackson.jaxrs.json.annotation.EndpointConfig</code>.
 * In Jackson 2.2 the first of these classes was moved to a different package,
 * and the second was replaced by <code>JsonEndpointConfig</code>.</li>
 * </ul>
 */
public ObjectWriter getObjectWriter(Annotation[] annotations) {
    AnnotationBundleKey key = new AnnotationBundleKey(annotations, AnnotationBundleKey.class);
    ObjectWriter writer = writers.get(key);
    if (writer == null) {
        // A quick hack to add custom serialization of the Reference type.
        SimpleModule module = new SimpleModule();
        module.addSerializer(new ReferenceSerializer(registry));
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(module);
        JsonEndpointConfig endpointConfig = JsonEndpointConfig.forWriting(mapper, annotations, null);
        writer = endpointConfig.getWriter();
        writers.put(key, writer);
    }
    return writer;
}

From source file:eu.trentorise.opendata.jackan.ckan.CkanClient.java

/**
 * Retrieves the Jackson object mapper. Internally, Object mapper is
 * initialized at first call./*from   ww w.j a  v a 2 s  .c  om*/
 */
static ObjectMapper getObjectMapper() {
    if (objectMapper == null) {
        objectMapper = new ObjectMapper();
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES)
                .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) // let's be tolerant
                .configure(MapperFeature.USE_GETTERS_AS_SETTERS, false) // not good for unmodifiable collections, if we will ever use any
                .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

        // When reading dates, Jackson defaults to using GMT for all processing unless specifically told otherwise, see http://wiki.fasterxml.com/JacksonFAQDateHandling
        // When writing dates, Jackson would add a Z for timezone by CKAN doesn't use it, i.e.  "2013-11-11T04:12:11.110868"                            so we removed it here
        objectMapper.setDateFormat(new SimpleDateFormat(CKAN_DATE_PATTERN)); // but this only works for Java Dates...

        // ...so taken solution from here: http://www.lorrin.org/blog/2013/06/28/custom-joda-time-dateformatter-in-jackson/
        objectMapper.registerModule(new JodaModule());
        objectMapper.registerModule(new GuavaModule());

        objectMapper.registerModule(new SimpleModule() {
            {
                addSerializer(DateTime.class, new StdSerializer<DateTime>(DateTime.class) {
                    @Override
                    public void serialize(DateTime value, JsonGenerator jgen, SerializerProvider provider)
                            throws IOException {
                        jgen.writeString(ckanDateFormatter.print(value));
                    }

                });

                addDeserializer(DateTime.class, CkanDateDeserializer.forType(DateTime.class));
            }
        });

    }
    return objectMapper;
}