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

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

Introduction

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

Prototype

public ObjectMapper setPropertyNamingStrategy(PropertyNamingStrategy s) 

Source Link

Document

Method for setting custom property naming strategy to use.

Usage

From source file:com.nike.cerberus.module.CerberusModule.java

/**
 * Object mapper for handling configuration objects in the config bucket.
 *
 * @return Object mapper//ww  w .  ja  va2 s. c  o m
 */
@Provides
@Singleton
@Named(CONFIG_OBJECT_MAPPER)
public ObjectMapper configObjectMapper() {
    final ObjectMapper om = new ObjectMapper();
    om.findAndRegisterModules();
    om.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    om.enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS);
    om.enable(SerializationFeature.INDENT_OUTPUT);
    om.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    om.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    return om;
}

From source file:client.DockerSshClient.java

/**
 * If the image reference does not exist, this function will throw a JsonFormatError as the
 * output will not contain the expected objects.
 *
 * @param imageReferences the image references
 *///from  ww w . j  av a 2s . c  om
@Override
public List<ImageInspection> inspectImages(final List<String> imageReferences)
        throws DockerDeploymentClientException {
    if (imageReferences.size() == 0) {
        return Collections.emptyList();
    }

    final ObjectMapper inspectionMapper = new ObjectMapper();

    inspectionMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.PropertyNamingStrategyBase() {
        static final long serialVersionUID = 1L;

        @Override
        public String translate(final String s) {
            // Json produced by docker uses capitalized words for property names.
            return s.substring(0, 1).toUpperCase(Locale.ENGLISH) + s.substring(1);
        }
    });

    final StringBuilder sb = new StringBuilder();
    sb.append(_dockerCmd).append(" inspect ");
    for (final String imageReference : imageReferences) {
        sb.append(imageReference).append(" ");
    }

    final String inspectionJson = sshExecAndGetOutput(sb.toString());

    final List<ImageInspection> inspections;
    try {
        inspections = inspectionMapper.readValue(inspectionJson,
                inspectionMapper.getTypeFactory().constructCollectionType(List.class, ImageInspection.class));
    } catch (final IOException e) {
        throw new DockerDeploymentClient.JsonFormatError("docker inspect output in unexpected format", e);
    }

    return inspections;
}

From source file:org.openmhealth.dsu.configuration.JacksonConfiguration.java

@Bean
public ObjectMapper objectMapper() {

    ObjectMapper objectMapper = new ObjectMapper();

    // serialise timestamps in an ISO8601 textual representation
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // serialise keys in snake_case
    objectMapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());

    return objectMapper;
}

From source file:com.aerofs.baseline.Service.java

public final void runWithConfiguration(T configuration) throws Exception {
    // initialize the validation subsystem
    ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class).configure()
            .buildValidatorFactory();//from w ww . j  av  a 2 s  . co m
    Validator validator = validatorFactory.getValidator();

    // validate the configuration
    Configuration.validateConfiguration(validator, configuration);

    // at this point we have a valid configuration
    // we can start logging to the correct location,
    // initialize common services, and start up
    // the jersey applications

    // reset the logging subsystem with the configured levels
    Logging.setupLogging(configuration.getLogging());

    // display the server banner if it exists
    displayBanner();

    // add a shutdown hook to release all resources cleanly
    Runtime.getRuntime().addShutdownHook(new Thread(this::shutdown));

    // setup some default metrics for the JVM
    MetricRegistries.getRegistry().register(Constants.JVM_BUFFERS,
            new BufferPoolMetricSet(ManagementFactory.getPlatformMBeanServer()));
    MetricRegistries.getRegistry().register(Constants.JVM_GC, new GarbageCollectorMetricSet());
    MetricRegistries.getRegistry().register(Constants.JVM_MEMORY, new MemoryUsageGaugeSet());
    MetricRegistries.getRegistry().register(Constants.JVM_THREADS, new ThreadStatesGaugeSet());

    // create the root service locator
    ServiceLocator rootLocator = ServiceLocatorFactory.getInstance().create("root");
    rootLocatorReference.set(rootLocator);

    // grab a reference to our system-wide class loader (we'll use this for the jersey service locators)
    ClassLoader classLoader = rootLocator.getClass().getClassLoader();

    // create the lifecycle manager
    LifecycleManager lifecycleManager = new LifecycleManager(rootLocator);
    lifecycleManagerReference.set(lifecycleManager);

    // after this point any services
    // added to the LifecycleManager will be
    // shut down cleanly

    // create and setup the system-wide Jackson object mapper
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);

    // create a few singleton objects
    Authenticators authenticators = new Authenticators();
    RegisteredCommands registeredCommands = new RegisteredCommands();
    RegisteredHealthChecks registeredHealthChecks = new RegisteredHealthChecks();

    // create the root environment
    Environment environment = new Environment(rootLocator, lifecycleManager, validator, mapper, authenticators,
            registeredCommands, registeredHealthChecks);

    // start configuring injectable objects
    // we'll be adding all instances and implementation classes to the root service locator
    // this makes them visible to the jersey applications

    environment.addBinder(new ConfigurationBinder<>(configuration, configuration.getClass()));
    environment.addBinder(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(name).to(String.class).named(Constants.SERVICE_NAME_INJECTION_KEY);
            bind(validator).to(Validator.class);
            bind(mapper).to(ObjectMapper.class);
            bind(environment).to(Environment.class);
            bind(lifecycleManager.getScheduledExecutorService()).to(ScheduledExecutorService.class);
            bind(lifecycleManager.getTimer()).to(Timer.class); // FIXME (AG): use our own timer interface
            bind(authenticators).to(Authenticators.class);
            bind(registeredCommands).to(RegisteredCommands.class);
            bind(registeredHealthChecks).to(RegisteredHealthChecks.class);
        }
    });

    // register some basic commands
    environment.registerCommand("gc", GarbageCollectionCommand.class);
    environment.registerCommand("metrics", MetricsCommand.class);
    environment.addAdminProvider(new AbstractBinder() {
        @Override
        protected void configure() {
            bind(GarbageCollectionCommand.class).to(GarbageCollectionCommand.class).in(Singleton.class);
            bind(MetricsCommand.class).to(MetricsCommand.class).in(Singleton.class);
        }
    });

    // add exception mappers that only apply to the admin environment
    environment.addAdminProvider(InvalidCommandExceptionMapper.class);

    // add the resources we expose via the admin api
    environment.addAdminResource(CommandsResource.class);
    environment.addAdminResource(HealthCheckResource.class);

    // create the two environments (admin and service)
    String adminName = name + "-" + Constants.ADMIN_IDENTIFIER;
    initializeJerseyApplication(adminName, classLoader, validator, mapper, environment.getAdminResourceConfig(),
            configuration.getAdmin());

    String serviceName = name + "-" + Constants.SERVICE_IDENTIFIER;
    initializeJerseyApplication(serviceName, classLoader, validator, mapper,
            environment.getServiceResourceConfig(), configuration.getService());

    // punt to subclasses for further configuration
    init(configuration, environment);

    // after this point we can't add any more jersey providers
    // resources, etc. and we're ready to expose our server to the world

    // list the objects that are registered with the root service locator
    listInjected(rootLocator);

    // initialize the admin http server
    if (configuration.getAdmin().isEnabled()) {
        ApplicationHandler adminHandler = new ApplicationHandler(environment.getAdminResourceConfig(), null,
                rootLocator);
        listInjected(adminHandler.getServiceLocator());
        HttpServer adminHttpServer = new HttpServer(Constants.ADMIN_IDENTIFIER, configuration.getAdmin(),
                lifecycleManager.getTimer(), adminHandler);
        lifecycleManager.add(adminHttpServer);
    }

    // initialize the service http server
    if (configuration.getService().isEnabled()) {
        ApplicationHandler serviceHandler = new ApplicationHandler(environment.getServiceResourceConfig(), null,
                rootLocator);
        listInjected(serviceHandler.getServiceLocator());
        HttpServer serviceHttpServer = new HttpServer(Constants.SERVICE_IDENTIFIER, configuration.getService(),
                lifecycleManager.getTimer(), serviceHandler);
        lifecycleManager.add(serviceHttpServer);
    }

    // finally, start up all managed services (which includes the two servers above)
    lifecycleManager.start();
}

From source file:org.springframework.session.data.mongo.JacksonMongoSessionConverter.java

private ObjectMapper buildObjectMapper() {
    ObjectMapper objectMapper = new ObjectMapper();

    // serialize fields instead of properties
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.NONE);
    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    // ignore unresolved fields (mostly 'principal')
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.setPropertyNamingStrategy(new MongoIdNamingStrategy());
    return objectMapper;
}

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);/*from   www  . ja va 2  s. c om*/

    //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.wealdtech.jackson.ObjectMapperFactory.java

/**
 * Build an objectmapper from a given configuration.
 *
 * @param configuration//  w  w  w .j  a v a 2s .  c  o m
 *          the objectmapper configuration
 * @return an objectmapper
 */
public ObjectMapper build(final ObjectMapperConfiguration configuration) {
    final ObjectMapper mapper = new ObjectMapper(configuration.getFactory().orNull());
    for (Module module : configuration.getModules()) {
        mapper.registerModule(module);
    }
    for (Map.Entry<JsonParser.Feature, Boolean> entry : configuration.getParserFeatures().entrySet()) {
        mapper.getFactory().configure(entry.getKey(), entry.getValue());
    }
    mapper.setInjectableValues(configuration.getInjectableValues());
    if (configuration.getPropertyNamingStrategy().isPresent()) {
        mapper.setPropertyNamingStrategy(configuration.getPropertyNamingStrategy().get());
    }
    if (configuration.getSerializationInclusion().isPresent()) {
        mapper.setSerializationInclusion(configuration.getSerializationInclusion().get());
    }

    return mapper;
}

From source file:org.trustedanalytics.cloud.cc.FeignClient.java

/**
 * Creates client applying default configuration and then customizations. Example:
 * <pre>//from  ww  w  .  j ava 2s . c  om
 * {@code
 * new FeignClient(apiUrl, builder -> builder.requestInterceptor(template ->
 * template.header("Authorization", "bearer " + token)));
 * }
 * </pre>
 * @param url endpoint url
 * @param customizations custom configuration that should be applied after defaults
 */
public FeignClient(String url, Function<Builder, Builder> customizations) {
    Objects.requireNonNull(url);
    Objects.requireNonNull(customizations);

    final ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.setPropertyNamingStrategy(new LowerCaseWithUnderscoresStrategy());

    // avoid duplication of slashes
    final String targetUrl = StringUtils.removeEnd(url, "/");

    // first applies defaults and then custom configuration
    final Builder builder = customizations.apply(Feign.builder().encoder(new JacksonEncoder())
            .decoder(new JacksonDecoder(mapper)).options(new Request.Options(CONNECT_TIMEOUT, READ_TIMEOUT))
            .logger(new ScramblingSlf4jLogger(FeignClient.class)).logLevel(feign.Logger.Level.BASIC)
            .errorDecoder(new CompositeErrorDecoder(new FeignErrorDecoderHandler("description"))));

    this.applicationResource = builder.target(CcApplicationResource.class, targetUrl);
    this.organizationResource = builder.target(CcOrganizationResource.class, targetUrl);
    this.serviceResource = builder.target(CcServiceResource.class, targetUrl);
    this.serviceBindingResource = builder.target(CcServiceBindingResource.class, targetUrl);
    this.spaceResource = builder.target(CcSpaceResource.class, targetUrl);
    this.userResource = builder.target(CcUserResource.class, targetUrl);
    this.buildpackResource = builder.target(CcBuildpacksResource.class, targetUrl);
    this.quotaResource = builder.target(CcQuotaResource.class, targetUrl);
}

From source file:org.springframework.http.converter.json.Jackson2ObjectMapperBuilder.java

/**
 * Configure an existing {@link ObjectMapper} instance with this builder's
 * settings. This can be applied to any number of {@code ObjectMappers}.
 * @param objectMapper the ObjectMapper to configure
 *//* w ww  .  ja v  a 2  s  .c  o  m*/
public void configure(ObjectMapper objectMapper) {
    Assert.notNull(objectMapper, "ObjectMapper must not be null");

    if (this.findModulesViaServiceLoader) {
        // Jackson 2.2+
        objectMapper.registerModules(ObjectMapper.findModules(this.moduleClassLoader));
    } else if (this.findWellKnownModules) {
        registerWellKnownModulesIfAvailable(objectMapper);
    }

    if (this.modules != null) {
        for (Module module : this.modules) {
            // Using Jackson 2.0+ registerModule method, not Jackson 2.2+ registerModules
            objectMapper.registerModule(module);
        }
    }
    if (this.moduleClasses != null) {
        for (Class<? extends Module> module : this.moduleClasses) {
            objectMapper.registerModule(BeanUtils.instantiateClass(module));
        }
    }

    if (this.dateFormat != null) {
        objectMapper.setDateFormat(this.dateFormat);
    }
    if (this.locale != null) {
        objectMapper.setLocale(this.locale);
    }
    if (this.timeZone != null) {
        objectMapper.setTimeZone(this.timeZone);
    }

    if (this.annotationIntrospector != null) {
        objectMapper.setAnnotationIntrospector(this.annotationIntrospector);
    }
    if (this.propertyNamingStrategy != null) {
        objectMapper.setPropertyNamingStrategy(this.propertyNamingStrategy);
    }
    if (this.defaultTyping != null) {
        objectMapper.setDefaultTyping(this.defaultTyping);
    }
    if (this.serializationInclusion != null) {
        objectMapper.setSerializationInclusion(this.serializationInclusion);
    }

    if (this.filters != null) {
        objectMapper.setFilterProvider(this.filters);
    }

    for (Class<?> target : this.mixIns.keySet()) {
        objectMapper.addMixIn(target, this.mixIns.get(target));
    }

    if (!this.serializers.isEmpty() || !this.deserializers.isEmpty()) {
        SimpleModule module = new SimpleModule();
        addSerializers(module);
        addDeserializers(module);
        objectMapper.registerModule(module);
    }

    customizeDefaultFeatures(objectMapper);
    for (Object feature : this.features.keySet()) {
        configureFeature(objectMapper, feature, this.features.get(feature));
    }

    if (this.handlerInstantiator != null) {
        objectMapper.setHandlerInstantiator(this.handlerInstantiator);
    } else if (this.applicationContext != null) {
        objectMapper.setHandlerInstantiator(
                new SpringHandlerInstantiator(this.applicationContext.getAutowireCapableBeanFactory()));
    }
}

From source file:test.xml.ReadFeatureXmlTest.java

/**
 * Sample output for feature 1:/* www  . java  2 s.c o m*/
 * 
{"id":"feature1","version":"0.1","name":"Feature #1","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"An example feature","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":null,"requires":null,"conflicts":null,"links":null}
 * 
 * Sample output for feature 2:
 * 
{"id":"feature2","version":"0.1","name":"Feature #2","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"A second example feature which depends on the first feature","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":null,"requires":{"feature_ref":{"id":"feature1","version":null}},"conflicts":null,"links":null}
 * 
 * Sample output for feature 3:
 * 
{"id":"feature3","version":"0.1","name":"Feature #3","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"A third example feature which depends on the first feature and conflicts with the second feature","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":null,"requires":{"feature_ref":{"id":"feature1","version":null}},"conflicts":{"feature_ref":{"id":"feature2","version":null}},"links":null}
 * 
 * Sample output for feature 4:
 * 
{"id":"feature4","version":"0.1","name":"Feature #4","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"An example feature","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":{"components":{"component":{"id":"componentA","version":"0.76","name":"Component A","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"An important sub-component","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":null,"requires":null,"conflicts":null,"links":null}}},"requires":null,"conflicts":null,"links":{"link":{"value":"mailto:feature4-users@provider.com","rel":"mailing list","type":null}}}
{"id":"feature4","version":"0.1","name":"Feature #4","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"An example feature","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":{"components":{"component":{"id":"componentA","version":"0.76","name":"Component A","provider":{"name":"Intel","url":"http://www.intel.com"},"description":"An important sub-component","license":{"copyright":"2014 Intel Corporation. All rights reserved.","url":"file:///LICENSE.TXT"},"includes":null,"requires":null,"conflicts":null,"links":null}}},"requires":null,"conflicts":null,"links":{"link":{"href":"mailto:feature4-users@provider.com","rel":"mailing list","type":null}}}
 * 
 * @throws Exception
 */
@Test
public void testReadFeatureType() throws Exception {
    InputStream in = getClass().getResourceAsStream("/feature-xml-examples/feature4.xml");
    FeatureType feature = fromXML(in, FeatureType.class);
    in.close();
    ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.LowerCaseWithUnderscoresStrategy());
    log.debug("feature1: {}", mapper.writeValueAsString(feature));
}