com.fasterxml.jackson.databind.MapperFeature Java Examples

The following examples show how to use com.fasterxml.jackson.databind.MapperFeature. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source Project: spring-boot-rest-api-helpers   Author: Nooul   File: CsvUtils.java    License: MIT License 11 votes vote down vote up
public static <T> List<T> read(Class<T> clazz, InputStream stream, boolean withHeaders, char separator) throws IOException {
    CsvMapper mapper = new CsvMapper();

    mapper.enable(CsvParser.Feature.TRIM_SPACES);
    mapper.enable(CsvParser.Feature.ALLOW_TRAILING_COMMA);
    mapper.enable(CsvParser.Feature.INSERT_NULLS_FOR_MISSING_COLUMNS);
    mapper.enable(CsvParser.Feature.SKIP_EMPTY_LINES);
    mapper.disable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    CsvSchema schema = mapper.schemaFor(clazz).withColumnReordering(true);
    ObjectReader reader;
    if (separator == '\t') {
        schema = schema.withColumnSeparator('\t');
    }
    else {
        schema = schema.withColumnSeparator(',');
    }
    if (withHeaders) {
        schema = schema.withHeader();
    }
    else {
        schema = schema.withoutHeader();
    }
    reader = mapper.readerFor(clazz).with(schema);
    return reader.<T>readValues(stream).readAll();
}
 
Example #2
Source Project: invest-openapi-java-sdk   Author: TinkoffCreditSystems   File: BaseContextImpl.java    License: Apache License 2.0 6 votes vote down vote up
public BaseContextImpl(@NotNull final OkHttpClient client,
                       @NotNull final String url,
                       @NotNull final String authToken,
                       @NotNull final Logger logger) {

    this.authToken = authToken;
    this.finalUrl = Objects.requireNonNull(HttpUrl.parse(url))
            .newBuilder()
            .addPathSegment(this.getPath())
            .build();
    this.client = client;
    this.logger = logger;
    this.mapper = new ObjectMapper();

    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.registerModule(new JavaTimeModule());
    mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
}
 
Example #3
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperBuilderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION,
					DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
					SerializationFeature.INDENT_OUTPUT)
			.featuresToDisable(MapperFeature.AUTO_DETECT_FIELDS,
					MapperFeature.AUTO_DETECT_GETTERS,
					MapperFeature.AUTO_DETECT_SETTERS,
					SerializationFeature.FAIL_ON_EMPTY_BEANS).build();
	assertNotNull(objectMapper);
	assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}
 
Example #4
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperFactoryBeanTests.java    License: MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	this.factory.setAutoDetectFields(false);
	this.factory.setAutoDetectGettersSetters(false);
	this.factory.setDefaultViewInclusion(false);
	this.factory.setFailOnEmptyBeans(false);
	this.factory.setIndentOutput(true);
	this.factory.afterPropertiesSet();

	ObjectMapper objectMapper = this.factory.getObject();

	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
	assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
 
Example #5
Source Project: frostmourne   Author: AutohomeCorp   File: JacksonObjectMapper.java    License: MIT License 6 votes vote down vote up
public static ObjectMapper settingCommonObjectMapper(ObjectMapper objectMapper) {
    objectMapper.setDateFormat(new StdDateFormat());
    objectMapper.setTimeZone(TimeZone.getDefault());

    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, false);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    objectMapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    objectMapper.configure(MapperFeature.INFER_PROPERTY_MUTATORS, false);
    objectMapper.configure(MapperFeature.ALLOW_FINAL_FIELDS_AS_MUTATORS, false);

    return objectMapper;
}
 
Example #6
Source Project: java-technology-stack   Author: codeEngraver   File: Jackson2ObjectMapperBuilder.java    License: MIT License 6 votes vote down vote up
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationFeature) {
		objectMapper.configure((SerializationFeature) feature, enabled);
	}
	else if (feature instanceof DeserializationFeature) {
		objectMapper.configure((DeserializationFeature) feature, enabled);
	}
	else if (feature instanceof MapperFeature) {
		objectMapper.configure((MapperFeature) feature, enabled);
	}
	else {
		throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
Example #7
Source Project: java-technology-stack   Author: codeEngraver   File: Jackson2ObjectMapperBuilderTests.java    License: MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
			.featuresToEnable(MapperFeature.DEFAULT_VIEW_INCLUSION,
					DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,
					SerializationFeature.INDENT_OUTPUT)
			.featuresToDisable(MapperFeature.AUTO_DETECT_FIELDS,
					MapperFeature.AUTO_DETECT_GETTERS,
					MapperFeature.AUTO_DETECT_SETTERS,
					SerializationFeature.FAIL_ON_EMPTY_BEANS).build();
	assertNotNull(objectMapper);
	assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}
 
Example #8
Source Project: java-technology-stack   Author: codeEngraver   File: Jackson2ObjectMapperFactoryBeanTests.java    License: MIT License 6 votes vote down vote up
@Test
public void booleanSetters() {
	this.factory.setAutoDetectFields(false);
	this.factory.setAutoDetectGettersSetters(false);
	this.factory.setDefaultViewInclusion(false);
	this.factory.setFailOnEmptyBeans(false);
	this.factory.setIndentOutput(true);
	this.factory.afterPropertiesSet();

	ObjectMapper objectMapper = this.factory.getObject();

	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertFalse(objectMapper.getDeserializationConfig().isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
	assertTrue(objectMapper.getSerializationConfig().isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertSame(Include.ALWAYS, objectMapper.getSerializationConfig().getSerializationInclusion());
}
 
Example #9
Source Project: qconfig   Author: qunarcorp   File: MapperBuilder.java    License: MIT License 6 votes vote down vote up
private static void configure(ObjectMapper om, Object feature, boolean state) {
    if (feature instanceof SerializationFeature)
        om.configure((SerializationFeature) feature, state);
    else if (feature instanceof DeserializationFeature)
        om.configure((DeserializationFeature) feature, state);
    else if (feature instanceof JsonParser.Feature)
        om.configure((JsonParser.Feature) feature, state);
    else if (feature instanceof JsonGenerator.Feature)
        om.configure((JsonGenerator.Feature) feature, state);
    else if (feature instanceof MapperFeature)
        om.configure((MapperFeature) feature, state);
    else if (feature instanceof Include) {
        if (state) {
            om.setSerializationInclusion((Include) feature);
        }
    }
}
 
Example #10
Source Project: openapi-generator   Author: OpenAPITools   File: SerializerUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String toYamlString(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    }
    SimpleModule module = createModule();
    try {
        ObjectMapper yamlMapper = Yaml.mapper().copy();
        // there is an unfortunate YAML condition where user inputs should be treated as strings (e.g. "1234_1234"), but in yaml this is a valid number and
        // removing quotes forcibly by default means we are potentially doing a data conversion resulting in an unexpected change to the user's YAML outputs.
        // We may allow for property-based enable/disable, retaining the default of enabled for backward compatibility.
        if (minimizeYamlQuotes) {
            ((YAMLFactory) yamlMapper.getFactory()).enable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        } else {
            ((YAMLFactory) yamlMapper.getFactory()).disable(YAMLGenerator.Feature.MINIMIZE_QUOTES);
        }
        return yamlMapper.registerModule(module)
                .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
                .writeValueAsString(openAPI)
                .replace("\r\n", "\n");
    } catch (JsonProcessingException e) {
        LOGGER.warn("Can not create yaml content", e);
    }
    return null;
}
 
Example #11
Source Project: openapi-generator   Author: OpenAPITools   File: SerializerUtils.java    License: Apache License 2.0 6 votes vote down vote up
public static String toJsonString(OpenAPI openAPI) {
    if (openAPI == null) {
        return null;
    }

    SimpleModule module = createModule();
    try {
        return Json.mapper()
                .copy()
                .registerModule(module)
                .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true)
                .writerWithDefaultPrettyPrinter()
                .writeValueAsString(openAPI)
                .replace("\r\n", "\n");
    } catch (JsonProcessingException e) {
        LOGGER.warn("Can not create json content", e);
    }
    return null;
}
 
Example #12
Source Project: hdw-dubbo   Author: JacksonTu   File: RedisConfig.java    License: Apache License 2.0 6 votes vote down vote up
@Bean
public RedisSerializer<Object> redisSerializer() {
    //创建JSON序列化器
    Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
            new Jackson2JsonRedisSerializer<>(Object.class);
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
    objectMapper.configure(MapperFeature.USE_ANNOTATIONS, false);
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    //TODO: 此项必须配置,否则会报java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to XXX
    objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance ,
            ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
    return jackson2JsonRedisSerializer;
}
 
Example #13
Source Project: raptor   Author: geekshop   File: SerializeTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void test() throws Exception {
    HelloRequest request = DemoMessageBuilder.getTestRequest();
    ObjectMapper objectMapper = new RaptorJacksonMessageConverter().getObjectMapper();
    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS,false);
    String json = objectMapper.writeValueAsString(request);

    System.out.println(json);

    Map<String, String> map = RaptorMessageUtils.transferMessageToMap(request);
    RequestTemplate requestTemplate = new RequestTemplate();
    map.forEach(requestTemplate::query);

    System.out.println(URLDecoder.decode(requestTemplate.queryLine(),"UTF-8"));

    Assert.assertFalse(json.contains("tdouble"));

}
 
Example #14
Source Project: spring-boot-data-geode   Author: spring-projects   File: PdxInstanceWrapperUnitTests.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void objectMapperConfigurationIsCorrect() {

	PdxInstanceWrapper wrapper = spy(PdxInstanceWrapper.from(mock(PdxInstance.class)));

	ObjectMapper mockObjectMapper = mock(ObjectMapper.class);

	doReturn(mockObjectMapper).when(wrapper).newObjectMapper();
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(DeserializationFeature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).configure(any(MapperFeature.class), anyBoolean());
	doReturn(mockObjectMapper).when(mockObjectMapper).findAndRegisterModules();

	ObjectMapper objectMapper = wrapper.getObjectMapper().orElse(null);

	assertThat(objectMapper).isNotNull();

	verify(mockObjectMapper, times(1)).configure(eq(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES), eq(false));
	verify(mockObjectMapper, times(1)).configure(eq(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES), eq(false));
	verify(mockObjectMapper, times(1)).configure(eq(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS), eq(true));
	verify(mockObjectMapper, times(1)).findAndRegisterModules();
	verifyNoMoreInteractions(mockObjectMapper);
}
 
Example #15
Source Project: quarkus   Author: quarkusio   File: ClientContextTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void testContextMarshalling() throws Exception {
    ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
            .configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);

    ObjectReader reader = mapper.readerFor(ClientContextImpl.class);

    ClientContext clientContext = reader.readValue(ctx);
    Assertions.assertNotNull(clientContext.getClient());
    Assertions.assertNotNull(clientContext.getCustom());
    Assertions.assertNotNull(clientContext.getEnvironment());

    Assertions.assertEquals("<client_id>", clientContext.getClient().getInstallationId());
    Assertions.assertEquals("<app_title>", clientContext.getClient().getAppTitle());
    Assertions.assertEquals("<app_version_name>", clientContext.getClient().getAppVersionName());
    Assertions.assertEquals("<app_version_code>", clientContext.getClient().getAppVersionCode());
    Assertions.assertEquals("<app_package_name>", clientContext.getClient().getAppPackageName());

    Assertions.assertEquals("world", clientContext.getCustom().get("hello"));
    Assertions.assertEquals("<platform>", clientContext.getEnvironment().get("platform"));

}
 
Example #16
Source Project: servicecomb-java-chassis   Author: apache   File: RestObjectMapper.java    License: Apache License 2.0 6 votes vote down vote up
public RestObjectMapper() {
  getFactory().disable(Feature.AUTO_CLOSE_SOURCE);
  // Enable features that can tolerance errors and not enable those make more constraints for compatible reasons.
  // Developers can use validation api to do more checks.
  disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
  disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
  // no view annotations shouldn't be included in JSON
  disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
  disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
  enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);

  SimpleModule module = new SimpleModule();
  // custom types
  module.addSerializer(JsonObject.class, new JsonObjectSerializer());
  registerModule(module);
  registerModule(new JavaTimeModule());
}
 
Example #17
Source Project: syndesis   Author: syndesisio   File: ActionProcessor.java    License: Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("PMD.AvoidSynchronizedAtMethodLevel") // as in super
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
    super.init(processingEnv);

    mapper = new ObjectMapper()
        .configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true)
        .configure(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY, true);

    annotationClass = mandatoryFindClass(SYNDESIS_ANNOTATION_CLASS_NAME);
    propertyAnnotationClass = mandatoryFindClass(SYNDESIS_PROPERTY_ANNOTATION_CLASS_NAME);
    propertyEnumAnnotationClass = mandatoryFindClass(SYNDESIS_PROPERTY_ENUM_ANNOTATION_CLASS_NAME);
    dataShapeVariantAnnotationClass = mandatoryFindClass(SYNDESIS_DATA_SHAPE_VARIANT_CLASS_NAME);
    dataShapeMetaAnnotationClass = mandatoryFindClass(SYNDESIS_DATA_SHAPE_META_CLASS_NAME);
    stepClass = findClass(SYNDESIS_STEP_CLASS_NAME);
    beanAnnotationClass = findClass(BEAN_ANNOTATION_CLASS_NAME);
    handlerAnnotationClass = mandatoryFindClass(CAMEL_HANDLER_ANNOTATION_CLASS_NAME);
    routeBuilderClass = mandatoryFindClass(CAMEL_ROUTE_BUILDER_CLASS_NAME_);
}
 
Example #18
Source Project: crnk-framework   Author: crnk-project   File: OASGenerator.java    License: Apache License 2.0 6 votes vote down vote up
@VisibleForTesting
static String generateOpenApiContent(OpenAPI openApi, OutputFormat outputFormat, Boolean sort) {
  if (sort) {
    ObjectMapper objectMapper = outputFormat.mapper();
    objectMapper.enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    objectMapper.enable(MapperFeature.SORT_PROPERTIES_ALPHABETICALLY);
    try {
      return objectMapper.writer(new DefaultPrettyPrinter()).writeValueAsString(openApi);
    } catch (JsonProcessingException e) {
      LOGGER.error("Sorting failed!");
      return outputFormat.pretty(openApi);
    }
  } else {
    return outputFormat.pretty(openApi);
  }
}
 
Example #19
Source Project: lams   Author: lamsfoundation   File: Jackson2ObjectMapperBuilder.java    License: GNU General Public License v2.0 6 votes vote down vote up
private void configureFeature(ObjectMapper objectMapper, Object feature, boolean enabled) {
	if (feature instanceof JsonParser.Feature) {
		objectMapper.configure((JsonParser.Feature) feature, enabled);
	}
	else if (feature instanceof JsonGenerator.Feature) {
		objectMapper.configure((JsonGenerator.Feature) feature, enabled);
	}
	else if (feature instanceof SerializationFeature) {
		objectMapper.configure((SerializationFeature) feature, enabled);
	}
	else if (feature instanceof DeserializationFeature) {
		objectMapper.configure((DeserializationFeature) feature, enabled);
	}
	else if (feature instanceof MapperFeature) {
		objectMapper.configure((MapperFeature) feature, enabled);
	}
	else {
		throw new FatalBeanException("Unknown feature class: " + feature.getClass().getName());
	}
}
 
Example #20
Source Project: soundwave   Author: pinterest   File: EsInstanceStore.java    License: Apache License 2.0 6 votes vote down vote up
public EsInstanceStore(String host, int port) {
  super(host, port);
  //This is required to let ES create the mapping of Date instead of long
  insertMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

  updateMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .addMixIn(getInstanceClass(), IgnoreCreatedTimeMixin.class);

  //Specific mapper to read EsDailySnapshotInstance from the index
  essnapshotinstanceMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
      .setPropertyNamingStrategy(new EsPropertyNamingStrategy(
          EsDailySnapshotInstance.class, EsInstanceStore.class))
      .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true);

}
 
Example #21
Source Project: soundwave   Author: pinterest   File: EsPropertyNamingStrategyTest.java    License: Apache License 2.0 6 votes vote down vote up
@Test
public void deserializeWithStrategy() throws Exception {
  ObjectMapper
      mapper =
      new ObjectMapper().configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false)
          .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
          .setPropertyNamingStrategy(new EsPropertyNamingStrategy(
              EsDailySnapshotInstance.class, EsInstanceStore.class))
          .configure(MapperFeature.ALLOW_EXPLICIT_PROPERTY_RENAMING, true);

  EsDailySnapshotInstance inst = mapper.readValue(doc, EsDailySnapshotInstance.class);
  Assert.assertEquals("coreapp-webapp-prod-0a018ef5", inst.getName());
  Assert.assertEquals("fixed", inst.getLifecycle());
  Assert.assertTrue(inst.getLaunchTime() != null);

}
 
Example #22
Source Project: caravan   Author: ctripcorp   File: FilterableJsonSerializer.java    License: Apache License 2.0 6 votes vote down vote up
public FilterableJsonSerializer(FilterableJsonSerializerConfig config) {
    NullArgumentChecker.DEFAULT.check(config, "config");

    ObjectMapper mapper = new ObjectMapper();

    SimpleModule module = new SimpleModule();
    module.setSerializerModifier(new FilterableBeanSerializerModifier(config));
    mapper.registerModule(module);

    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false);
    mapper.configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, false);
    mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
    mapper.configure(Feature.AUTO_CLOSE_TARGET, false);
    mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);

    _mapper = mapper;
}
 
Example #23
Source Project: qpid-broker-j   Author: apache   File: ObjectMapperFactory.java    License: Apache License 2.0 6 votes vote down vote up
public ObjectMapper createObjectMapper()
{
    SimpleModule module = new SimpleModule();
    module.addDeserializer(PropertyValue.class, new PropertyValueDeserializer());
    module.addSerializer(SimplePropertyValue.class, new SimplePropertyValueSerializer());

    ObjectMapper objectMapper = new ObjectMapper();

    objectMapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);

    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

    objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
    objectMapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);

    objectMapper.configure(MapperFeature.AUTO_DETECT_GETTERS, false);
    objectMapper.registerModule(module);

    objectMapper.registerModule(module);

    return objectMapper;
}
 
Example #24
Source Project: data-highway   Author: HotelsDotCom   File: OfframpConfiguration.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper jsonMapper() {
  return new ObjectMapper()
      .registerModule(new SchemaSerializationModule())
      .registerModule(Event.module())
      .registerModule(new JavaTimeModule())
      .disable(MapperFeature.DEFAULT_VIEW_INCLUSION)
      .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
      .disable(SerializationFeature.WRITE_DATE_KEYS_AS_TIMESTAMPS);
}
 
Example #25
Source Project: spring-boot-data-geode   Author: spring-projects   File: JacksonJsonToObjectConverterUnitTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void objectMapperConfigurationIsCorrect() {

	ObjectMapper objectMapper = this.converter.getObjectMapper();

	assertThat(objectMapper).isNotNull();
	assertThat(objectMapper.isEnabled(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS)).isTrue();
	assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES)).isFalse();
	assertThat(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)).isFalse();
}
 
Example #26
Source Project: jkube   Author: eclipse   File: AssemblyConfigurationTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Verifies that deserialization works for raw deserialization (Maven-Plexus) disregarding annotations.
 *
 * Especially designed to catch problems if Enum names are changed.
 */
@Test
public void rawDeserialization() throws IOException {
  // Given
  final ObjectMapper mapper = new ObjectMapper();
  mapper.configure(MapperFeature.USE_ANNOTATIONS, false);
  // When
  final AssemblyConfiguration result = mapper.readValue(
      AssemblyConfigurationTest.class.getResourceAsStream("/assembly-configuration.json"),
      AssemblyConfiguration.class
  );
  // Then
  assertThat(result, notNullValue());
  assertThat(result.getName(), is("assembly"));
  assertThat(result.getTargetDir(), is("target"));
  assertThat(result.getDescriptor(), is("assDescriptor"));
  assertThat(result.getDescriptorRef(), is("ass reference"));
  assertThat(result.getExportTargetDir(), is(false));
  assertThat(result.isExcludeFinalOutputArtifact(), is(true));
  assertThat(result.getPermissions(), is(AssemblyConfiguration.PermissionMode.exec));
  assertThat(result.getPermissionsRaw(), is("exec"));
  assertThat(result.getMode(), is(AssemblyMode.zip));
  assertThat(result.getModeRaw(), is("zip"));
  assertThat(result.getUser(), is("root"));
  assertThat(result.getTarLongFileMode(), is("posix"));
  assertThat(result.getInline(), notNullValue());
}
 
Example #27
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperBuilder.java    License: MIT License 5 votes vote down vote up
private void customizeDefaultFeatures(ObjectMapper objectMapper) {
	if (!this.features.containsKey(MapperFeature.DEFAULT_VIEW_INCLUSION)) {
		configureFeature(objectMapper, MapperFeature.DEFAULT_VIEW_INCLUSION, false);
	}
	if (!this.features.containsKey(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)) {
		configureFeature(objectMapper, DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
}
 
Example #28
Source Project: graphql-java-datetime   Author: donbeave   File: ContextHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Bean
public ObjectMapper objectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, true);

    return mapper;
}
 
Example #29
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperBuilderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void defaultProperties() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
	assertNotNull(objectMapper);
	assertFalse(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertFalse(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS));
	assertTrue(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertFalse(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertTrue(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}
 
Example #30
Source Project: spring-analysis-note   Author: Vip-Augus   File: Jackson2ObjectMapperBuilderTests.java    License: MIT License 5 votes vote down vote up
@Test
public void propertiesShortcut() {
	ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().autoDetectFields(false)
			.defaultViewInclusion(true).failOnUnknownProperties(true).failOnEmptyBeans(false)
			.autoDetectGettersSetters(false).indentOutput(true).build();
	assertNotNull(objectMapper);
	assertTrue(objectMapper.isEnabled(MapperFeature.DEFAULT_VIEW_INCLUSION));
	assertTrue(objectMapper.isEnabled(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_FIELDS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_IS_GETTERS));
	assertFalse(objectMapper.isEnabled(MapperFeature.AUTO_DETECT_SETTERS));
	assertTrue(objectMapper.isEnabled(SerializationFeature.INDENT_OUTPUT));
	assertFalse(objectMapper.isEnabled(SerializationFeature.FAIL_ON_EMPTY_BEANS));
}