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

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

Introduction

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

Prototype

public SerializationConfig getSerializationConfig() 

Source Link

Document

Method that returns the shared default SerializationConfig object that defines configuration settings for serialization.

Usage

From source file:capital.scalable.restdocs.jackson.FieldDocumentationGeneratorTest.java

@Test
public void testGenerateDocumentationForFieldResolution() throws Exception {
    // given/*  w ww  . j a v  a  2s.c o  m*/
    // different mapper for custom field resolution
    ObjectMapper mapper = new ObjectMapper();
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.PUBLIC_ONLY));

    ConstraintReader constraintReader = mock(ConstraintReader.class);

    JavadocReader javadocReader = mock(JavadocReader.class);
    // comment on field directly
    when(javadocReader.resolveFieldComment(FieldCommentResolution.class, "location")).thenReturn("A location");
    // comment on getter instead of field
    when(javadocReader.resolveMethodComment(FieldCommentResolution.class, "getType")).thenReturn("A type");
    // comment on field instead of getter
    when(javadocReader.resolveFieldComment(FieldCommentResolution.class, "uri")).thenReturn("A uri");
    when(javadocReader.resolveFieldComment(FieldCommentResolution.class, "secured"))
            .thenReturn("A secured flag");

    FieldDocumentationGenerator generator = new FieldDocumentationGenerator(mapper.writer(), javadocReader,
            constraintReader);
    Type type = FieldCommentResolution.class;

    // when
    List<ExtendedFieldDescriptor> fieldDescriptions = cast(
            generator.generateDocumentation(type, mapper.getTypeFactory()));

    // then
    assertThat(fieldDescriptions.size(), is(4));
    // field comment
    assertThat(fieldDescriptions.get(0), is(descriptor("location", "String", "A location", "true")));
    // getter comment
    assertThat(fieldDescriptions.get(1), is(descriptor("type", "String", "A type", "true")));
    // field comment
    assertThat(fieldDescriptions.get(2), is(descriptor("uri", "String", "A uri", "true")));
    assertThat(fieldDescriptions.get(3), is(descriptor("secured", "Boolean", "A secured flag", "true")));
}

From source file:net.logstash.logback.marker.ObjectFieldsAppendingMarker.java

/**
 * Gets a serializer that will write the {@link #object} unwrapped. 
 *///from   www . jav  a2 s.c  o  m
private JsonSerializer<Object> getBeanSerializer(ObjectMapper mapper) throws JsonMappingException {

    JsonSerializer<Object> jsonSerializer = beanSerializers.get(object.getClass());

    if (jsonSerializer == null) {
        SerializerProvider serializerProvider = getSerializerProvider(mapper);
        JsonSerializer<Object> newSerializer = mapper.getSerializerFactory()
                .createSerializer(serializerProvider,
                        mapper.getSerializationConfig().constructType(object.getClass()))
                .unwrappingSerializer(NameTransformer.NOP);

        if (newSerializer instanceof ResolvableSerializer) {
            ((ResolvableSerializer) newSerializer).resolve(serializerProvider);
        }

        JsonSerializer<Object> existingSerializer = beanSerializers.putIfAbsent(object.getClass(),
                newSerializer);

        jsonSerializer = (existingSerializer == null) ? newSerializer : existingSerializer;
    }
    return jsonSerializer;

}

From source file:info.archinnov.achilles.configuration.ArgumentExtractorTest.java

@Test
public void should_init_default_object_factory_mapper() throws Exception {
    JacksonMapperFactory actual = extractor.initObjectMapperFactory(configMap);

    assertThat(actual).isNotNull();/* w w  w.  j  a  va  2s .  c  o m*/

    ObjectMapper mapper = actual.getMapper(Integer.class);

    assertThat(mapper).isNotNull();
    assertThat(mapper.getSerializationConfig().getSerializationInclusion())
            .isEqualTo(JsonInclude.Include.NON_NULL);
    assertThat(mapper.getDeserializationConfig().isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES))
            .isFalse();
    Collection<AnnotationIntrospector> ais = mapper.getSerializationConfig().getAnnotationIntrospector()
            .allIntrospectors();

    assertThat(ais).hasSize(2);
    Iterator<AnnotationIntrospector> iterator = ais.iterator();

    assertThat(iterator.next()).isInstanceOfAny(JacksonAnnotationIntrospector.class,
            JaxbAnnotationIntrospector.class);
    assertThat(iterator.next()).isInstanceOfAny(JacksonAnnotationIntrospector.class,
            JaxbAnnotationIntrospector.class);
}

From source file:com.microsoft.rest.serializer.JacksonMapperAdapter.java

/**
 * Initializes an instance of JacksonMapperAdapter with default configurations
 * applied to the object mapper.//from   w  w  w  .j ava2 s  .c om
 *
 * @param mapper the object mapper to use.
 */
protected void initializeObjectMapper(ObjectMapper mapper) {
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
            .configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true)
            .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL).registerModule(new JodaModule())
            .registerModule(ByteArraySerializer.getModule()).registerModule(DateTimeSerializer.getModule())
            .registerModule(DateTimeRfc1123Serializer.getModule())
            .registerModule(HeadersSerializer.getModule());
    mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withIsGetterVisibility(JsonAutoDetect.Visibility.NONE));
}

From source file:com.arpnetworking.jackson.ObjectMapperFactoryTest.java

@Test
public void testNewInstance() {
    final ObjectMapper objectMapper1 = ObjectMapperFactory.createInstance();
    final ObjectMapper objectMapper2 = ObjectMapperFactory.createInstance();
    Assert.assertNotSame(objectMapper1, objectMapper2);

    // Deserialization feature
    objectMapper1.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
    objectMapper2.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    Assert.assertTrue(objectMapper1.getDeserializationConfig()
            .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
    Assert.assertFalse(objectMapper2.getDeserializationConfig()
            .isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));

    // Serialization feature
    objectMapper1.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper2.configure(SerializationFeature.INDENT_OUTPUT, false);
    Assert.assertTrue(objectMapper1.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
    Assert.assertFalse(objectMapper2.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
}

From source file:com.arpnetworking.tsdaggregator.configuration.PipelineConfiguration.java

/**
 * Create an <code>ObjectMapper</code> for Pipeline configuration.
 *
 * @param injector The Guice <code>Injector</code> instance.
 * @return An <code>ObjectMapper</code> for Pipeline configuration.
 *///from  www.jav a2s  .co  m
public static ObjectMapper createObjectMapper(final Injector injector) {
    final ObjectMapper objectMapper = ObjectMapperFactory.createInstance();

    final SimpleModule module = new SimpleModule("Pipeline");
    BuilderDeserializer.addTo(module, PipelineConfiguration.class);

    final Set<Class<? extends Sink>> sinkClasses = INTERFACE_DATABASE.findClassesWithInterface(Sink.class);
    for (final Class<? extends Sink> sinkClass : sinkClasses) {
        BuilderDeserializer.addTo(module, sinkClass);
    }

    final Set<Class<? extends Source>> sourceClasses = INTERFACE_DATABASE
            .findClassesWithInterface(Source.class);
    for (final Class<? extends Source> sourceClass : sourceClasses) {
        BuilderDeserializer.addTo(module, sourceClass);
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    final Set<Class<? extends Parser<?>>> parserClasses = INTERFACE_DATABASE
            .findClassesWithInterface((Class) Parser.class);
    for (final Class<? extends Parser<?>> parserClass : parserClasses) {
        BuilderDeserializer.addTo(module, parserClass);
    }

    final Set<Class<? extends DynamicConfigurationFactory>> dcFactoryClasses = INTERFACE_DATABASE
            .findClassesWithInterface(DynamicConfigurationFactory.class);
    for (final Class<? extends DynamicConfigurationFactory> dcFactoryClass : dcFactoryClasses) {
        BuilderDeserializer.addTo(module, dcFactoryClass);
    }

    objectMapper.registerModules(module);

    final GuiceAnnotationIntrospector guiceIntrospector = new GuiceAnnotationIntrospector();
    objectMapper.setInjectableValues(new GuiceInjectableValues(injector));
    objectMapper.setAnnotationIntrospectors(
            new AnnotationIntrospectorPair(guiceIntrospector,
                    objectMapper.getSerializationConfig().getAnnotationIntrospector()),
            new AnnotationIntrospectorPair(guiceIntrospector,
                    objectMapper.getDeserializationConfig().getAnnotationIntrospector()));

    return objectMapper;
}

From source file:org.deeplearning4j.nn.conf.ComputationGraphConfiguration.java

/**
 * Create a computation graph configuration from json
 *
 * @param json the neural net configuration from json
 * @return {@link org.deeplearning4j.nn.conf.ComputationGraphConfiguration}
 *//*www .  j a va 2s. c o  m*/
public static ComputationGraphConfiguration fromJson(String json) {
    //As per MultiLayerConfiguration.fromJson()
    ObjectMapper mapper = NeuralNetConfiguration.mapper();
    try {
        return mapper.readValue(json, ComputationGraphConfiguration.class);
    } catch (IOException e) {
        //No op - try again after adding new subtypes
    }

    //Try: programmatically registering JSON subtypes for GraphVertex classes. This allows users to to add custom GraphVertex
    // implementations without needing to manually register subtypes
    //First: get all registered subtypes
    AnnotatedClass ac = AnnotatedClass.construct(GraphVertex.class,
            mapper.getSerializationConfig().getAnnotationIntrospector(), null);
    Collection<NamedType> types = mapper.getSubtypeResolver().collectAndResolveSubtypes(ac,
            mapper.getSerializationConfig(), mapper.getSerializationConfig().getAnnotationIntrospector());
    Set<Class<?>> registeredSubtypes = new HashSet<>();
    for (NamedType nt : types) {
        registeredSubtypes.add(nt.getType());
    }

    //Second: get all subtypes of GraphVertex using reflection
    Reflections reflections = new Reflections();
    Set<Class<? extends GraphVertex>> subTypes = reflections.getSubTypesOf(GraphVertex.class);

    //Third: register all subtypes that are not already registered
    List<NamedType> toRegister = new ArrayList<>();
    for (Class<? extends GraphVertex> c : subTypes) {
        if (!registeredSubtypes.contains(c)) {
            String name;
            if (ClassUtils.isInnerClass(c)) {
                Class<?> c2 = c.getDeclaringClass();
                name = c2.getSimpleName() + "$" + c.getSimpleName();
            } else {
                name = c.getSimpleName();
            }
            toRegister.add(new NamedType(c, name));
        }
    }
    mapper = NeuralNetConfiguration.reinitMapperWithSubtypes(toRegister);

    try {
        return mapper.readValue(json, ComputationGraphConfiguration.class);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.openengsb.core.util.JsonUtils.java

public static ObjectMapper createObjectMapperWithIntroSpectors() {
    ObjectMapper mapper = new ObjectMapper();
    AnnotationIntrospector primaryIntrospector = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondaryIntrospector = new JaxbAnnotationIntrospector(mapper.getTypeFactory());
    AnnotationIntrospector introspector = new AnnotationIntrospectorPair(primaryIntrospector,
            secondaryIntrospector);/*  w w w .ja v  a  2s  .com*/
    mapper.getDeserializationConfig().withAppendedAnnotationIntrospector(introspector);
    mapper.getSerializationConfig().withAppendedAnnotationIntrospector(introspector);
    return mapper;
}

From source file:uk.gov.gchq.gaffer.rest.service.GraphConfigurationService.java

@SuppressFBWarnings(value = "REC_CATCH_EXCEPTION", justification = "Need to wrap all runtime exceptions before they are given to the user")
@Override//from ww w .j  a  v  a2  s .  c  o m
public Set<String> getSerialisedFields(final String className) {
    final Class<?> clazz;
    try {
        clazz = Class.forName(className);
    } catch (final Exception e) {
        throw new IllegalArgumentException("Class name was not recognised: " + className, e);
    }

    final ObjectMapper mapper = new ObjectMapper();
    final JavaType type = mapper.getTypeFactory().constructType(clazz);
    final BeanDescription introspection = mapper.getSerializationConfig().introspect(type);
    final List<BeanPropertyDefinition> properties = introspection.findProperties();

    final Set<String> fields = new HashSet<>();
    for (final BeanPropertyDefinition property : properties) {
        fields.add(property.getName());
    }

    return fields;
}