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

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

Introduction

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

Prototype

public ObjectMapper disable(SerializationFeature f) 

Source Link

Document

Method for enabling specified DeserializationConfig features.

Usage

From source file:com.nonninz.robomodel.RoboManager.java

public <C extends RoboModelCollection<T>> C createCollection(String json, Class<C> klass) {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(MapperFeature.USE_ANNOTATIONS, true);
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    try {/*from w ww  .j a  v  a  2 s  . co  m*/
        final C result = mapper.readValue(json, klass);
        result.setContext(mContext);
        return result;
    } catch (Exception e) {
        throw new JsonException("Error while parsing JSON", e);
    }
}

From source file:org.killbill.billing.server.listeners.KillbillPlatformGuiceListener.java

protected void initializeGuice(final ServletContextEvent event) {
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.registerModule(new JodaModule());
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    guiceModules = ImmutableList.<Module>of(getServletModule(), getJacksonModule(),
            new JMXModule(KillbillHealthcheck.class, NotificationQueueService.class, PersistentBus.class),
            new StatsModule(METRICS_SERVLETS_PATHS.get(0), METRICS_SERVLETS_PATHS.get(1),
                    METRICS_SERVLETS_PATHS.get(2), METRICS_SERVLETS_PATHS.get(3),
                    ImmutableList.<Class<? extends HealthCheck>>of(KillbillHealthcheck.class)),
            getModule(event.getServletContext()));

    // Start the Guice machinery
    super.contextInitialized(event);

    injector = injector(event);/* w  ww . j  a v a 2  s .com*/
    event.getServletContext().setAttribute(Injector.class.getName(), injector);

    // Already started at this point - we just need the instance for shutdown
    embeddedDB = injector.getInstance(EmbeddedDB.class);

    killbillLifecycle = injector.getInstance(Lifecycle.class);
    killbillBusService = injector.getInstance(BusService.class);
}

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

/**
 * Object mapper for handling configuration objects in the config bucket.
 *
 * @return Object mapper//from   w w w  . j  a v a2s .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:com.apteligent.ApteligentJavaClient.java

private ObjectMapper getObjectMapper() {
    // configure and return ObjectMapper for JSON->Java Object de-serialization
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.setVisibilityChecker(mapper.getSerializationConfig().getDefaultVisibilityChecker()
            .withFieldVisibility(JsonAutoDetect.Visibility.ANY)
            .withGetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withSetterVisibility(JsonAutoDetect.Visibility.NONE)
            .withCreatorVisibility(JsonAutoDetect.Visibility.NONE));
    mapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);
    return mapper;
}

From source file:com.bazaarvoice.jsonpps.PrettyPrintJson.java

public void prettyPrint(List<File> inputFiles, File outputFile) throws IOException {
    JsonFactory factory = new JsonFactory();
    factory.disable(JsonFactory.Feature.INTERN_FIELD_NAMES);
    if (!strict) {
        factory.enable(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER);
        factory.enable(JsonParser.Feature.ALLOW_COMMENTS);
        factory.enable(JsonParser.Feature.ALLOW_NON_NUMERIC_NUMBERS);
        factory.enable(JsonParser.Feature.ALLOW_NUMERIC_LEADING_ZEROS);
        factory.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS);
        factory.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES);
    }//from w w  w . ja v  a 2s  .c  o m

    ObjectMapper mapper = null;
    if (sortKeys) {
        mapper = new ObjectMapper(factory);
        mapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
        mapper.disable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    }

    // Open the output stream and create the Json emitter.
    JsonGenerator generator;
    File tempOutputFile = null;
    if (STDINOUT.equals(outputFile)) {
        generator = factory.createGenerator(stdout, JsonEncoding.UTF8);
    } else if (!caseInsensitiveContains(inputFiles, outputFile)) {
        generator = factory.createGenerator(outputFile, JsonEncoding.UTF8);
    } else {
        // Writing to an input file.. use a temp file to stage the output until we're done.
        tempOutputFile = getTemporaryFileFor(outputFile);
        generator = factory.createGenerator(tempOutputFile, JsonEncoding.UTF8);
    }
    try {
        // Separate top-level objects by a newline in the output.
        String newline = System.getProperty("line.separator");
        generator.setPrettyPrinter(new DefaultPrettyPrinter(newline));

        if (wrap) {
            generator.writeStartArray();
        }

        for (File inputFile : inputFiles) {
            JsonParser parser;
            if (STDINOUT.equals(inputFile)) {
                parser = factory.createParser(stdin);
            } else {
                parser = factory.createParser(inputFile);
            }
            try {
                while (parser.nextToken() != null) {
                    copyCurrentStructure(parser, mapper, 0, generator);
                }
            } finally {
                parser.close();
            }
        }

        if (wrap) {
            generator.writeEndArray();
        }

        generator.writeRaw(newline);
    } finally {
        generator.close();
    }
    if (tempOutputFile != null && !tempOutputFile.renameTo(outputFile)) {
        System.err.println("error: unable to rename temporary file to output: " + outputFile);
        System.exit(1);
    }
}

From source file:com.ikanow.aleph2.data_model.utils.TestBeanTemplateUtils.java

@Test
public void testNumberDeserializer() {
    TestDeserializeBean bean1 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1.0}}", TestDeserializeBean.class).get();
    JsonNode jn1 = BeanTemplateUtils.toJson(bean1);

    assertEquals("{\"testMap\":{\"test\":1}}", jn1.toString());

    TestDeserializeBean bean2 = BeanTemplateUtils.from(
            "{\"testMap\":{\"test\":10000000000000,\"test1\":10000000000000.1,\"test2\":\"some string\"}}",
            TestDeserializeBean.class).get();
    JsonNode jn2 = BeanTemplateUtils.toJson(bean2);

    assertEquals(/*from  w w  w.  ja  va  2s .c  o m*/
            "{\"testMap\":{\"test\":10000000000000,\"test1\":1.00000000000001E13,\"test2\":\"some string\"}}",
            jn2.toString());

    TestDeserializeBean bean3 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1e7, \"test2\":1.0000000000000E7,\"test3\":1E19}}",
                    TestDeserializeBean.class)
            .get();
    JsonNode jn3 = BeanTemplateUtils.toJson(bean3);

    assertEquals("{\"testMap\":{\"test\":10000000,\"test2\":1.0E7,\"test3\":1.0E19}}", jn3.toString());

    //Mapper without the Number deserializer to make sure the double values are staying the same
    ObjectMapper plainMapper = new ObjectMapper();
    plainMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    plainMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    plainMapper.setSerializationInclusion(Include.NON_NULL);

    //Checking that the deserializer doesn't break existing double values
    TestDeserializeBean bean4 = BeanTemplateUtils.from(
            "{\"testMap\":{\"test\":1e7, \"test2\":1.0000000000000E7,\"test3\":1.1,\"test4\":10000000000000.1,\"test4\":6e9,\"test5\":6e300,\"test5\":1E7 }}",
            TestDeserializeBean.class).get();
    JsonNode number_deserialized = BeanTemplateUtils.toJson(bean4);
    JsonNode plain = plainMapper.valueToTree(bean4);

    assertEquals(plain.toString(), number_deserialized.toString());

    // Just check it doesn't mess up actual double deserialization:

    TestDeserializeBean2 bean2_1 = BeanTemplateUtils
            .from("{\"testMap\":{\"test\":1.0}}", TestDeserializeBean2.class).get();
    JsonNode jn2_1 = BeanTemplateUtils.toJson(bean2_1);

    assertEquals("{\"testMap\":{\"test\":1.0}}", jn2_1.toString());

}

From source file:com.fitbur.docker.client.internal.ObjectMapperProvider.java

@PerLookup
@Override//from   www  .  j  a  va2s. co m
public ObjectMapper provide() {
    ObjectMapper mapper = new ObjectMapper();

    mapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY)
            .setSerializationInclusion(JsonInclude.Include.NON_NULL);

    mapper.enable(MapperFeature.USE_ANNOTATIONS).enable(MapperFeature.AUTO_DETECT_GETTERS)
            .enable(MapperFeature.AUTO_DETECT_SETTERS).enable(MapperFeature.AUTO_DETECT_IS_GETTERS)
            .enable(MapperFeature.AUTO_DETECT_FIELDS).enable(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS);

    mapper.disable(SerializationFeature.INDENT_OUTPUT).enable(SerializationFeature.WRITE_EMPTY_JSON_ARRAYS)
            .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);

    mapper.disable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT)
            .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
            .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);

    mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true)
            .configure(JsonGenerator.Feature.WRITE_NUMBERS_AS_STRINGS, true);

    return mapper;
}

From source file:com.offbytwo.jenkins.client.JenkinsHttpClient.java

private ObjectMapper getDefaultMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.disable(FAIL_ON_UNKNOWN_PROPERTIES);
    return mapper;
}

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

/**
 * Creates client applying default configuration and then customizations. Example:
 * <pre>//from  www .  ja  v a 2  s.  c  o  m
 * {@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:nu.yona.server.CoreConfiguration.java

@Bean
@Primary/*from   w  w w  . j a  v a  2 s . co  m*/
ObjectMapper objectMapper() {
    // HATEOAS disables the default Spring configuration options described at
    // https://docs.spring.io/spring-boot/docs/current/reference/html/howto-spring-mvc.html#howto-customize-the-jackson-objectmapper
    // See https://github.com/spring-projects/spring-hateoas/issues/333.
    // We fix this by applying the Spring configurator on the HATEOAS object mapper
    // See also
    // https://github.com/spring-projects/spring-boot/blob/v1.3.2.RELEASE/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/hateoas/HypermediaAutoConfiguration.java
    // which already seems to do this but does not work
    ObjectMapper springHateoasObjectMapper = beanFactory.getBean(SPRING_HATEOAS_OBJECT_MAPPER,
            ObjectMapper.class);
    Jackson2ObjectMapperBuilder builder = beanFactory.getBean(Jackson2ObjectMapperBuilder.class);
    builder.configure(springHateoasObjectMapper);

    // By default, Jackson converts dates to UTC. This causes issues when passing inactivity creation requests from the app
    // service to the analysis engine service.
    springHateoasObjectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);

    // This way, the JsonView annotations on the controlers work properly
    springHateoasObjectMapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION);

    return springHateoasObjectMapper;
}