Java Code Examples for com.fasterxml.jackson.databind.ObjectMapper#setPropertyNamingStrategy()

The following examples show how to use com.fasterxml.jackson.databind.ObjectMapper#setPropertyNamingStrategy() . 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 File: JacksonJson.java    From gitlab4j-api with MIT License 6 votes vote down vote up
public JacksonJson() {

        objectMapper = new ObjectMapper();

        objectMapper.setSerializationInclusion(Include.NON_NULL);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

        SimpleModule module = new SimpleModule("GitLabApiJsonModule");
        module.addSerializer(Date.class, new JsonDateSerializer());
        module.addDeserializer(Date.class, new JsonDateDeserializer());
        objectMapper.registerModule(module);

        setMapper(objectMapper);
    }
 
Example 2
Source File: JacksonJson.java    From choerodon-starters with Apache License 2.0 6 votes vote down vote up
public JacksonJson() {

        objectMapper = new ObjectMapper();

        objectMapper.setSerializationInclusion(Include.NON_NULL);
        objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.configure(SerializationFeature.WRITE_ENUMS_USING_TO_STRING, true);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        objectMapper.configure(DeserializationFeature.READ_ENUMS_USING_TO_STRING, true);

        SimpleModule module = new SimpleModule("GitLabApiJsonModule");
        module.addSerializer(Date.class, new JsonDateSerializer());
        module.addDeserializer(Date.class, new JsonDateDeserializer());
        objectMapper.registerModule(module);
    }
 
Example 3
Source File: SwaggerGenMojo.java    From herd with Apache License 2.0 6 votes vote down vote up
/**
 * Creates the YAML file in the output location based on the Swagger metadata.
 *
 * @param swagger the Swagger metadata.
 *
 * @throws MojoExecutionException if any error was encountered while writing the YAML information to the file.
 */
private void createYamlFile(Swagger swagger) throws MojoExecutionException
{
    String yamlOutputLocation = outputDirectory + "/" + outputFilename;
    try
    {
        getLog().debug("Creating output YAML file \"" + yamlOutputLocation + "\"");

        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
        objectMapper.setPropertyNamingStrategy(new SwaggerNamingStrategy());
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        objectMapper.writeValue(new File(yamlOutputLocation), swagger);
    }
    catch (IOException e)
    {
        throw new MojoExecutionException("Error creating output YAML file \"" + yamlOutputLocation + "\". Reason: " + e.getMessage(), e);
    }
}
 
Example 4
Source File: JacksonUtil.java    From archie with Apache License 2.0 6 votes vote down vote up
/**
 * Configure an existing object mapper to work with Archie RM and AOM Objects.
 * Indentation is enabled. Feel free to disable again in your own code.
 * @param objectMapper
 */
public static void configureObjectMapper(ObjectMapper objectMapper) {
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT);
    objectMapper.enable(SerializationFeature.FLUSH_AFTER_WRITE_VALUE);
    objectMapper.disable(SerializationFeature.WRITE_NULL_MAP_VALUES);
    objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
    objectMapper.enable(DeserializationFeature.UNWRAP_SINGLE_VALUE_ARRAYS);
    objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    //objectMapper.

    objectMapper.registerModule(new JavaTimeModule());


    TypeResolverBuilder typeResolverBuilder = new ArchieTypeResolverBuilder()
            .init(JsonTypeInfo.Id.NAME, new OpenEHRTypeNaming())
            .typeProperty("@type")
            .typeIdVisibility(true)
            .inclusion(JsonTypeInfo.As.PROPERTY);

    objectMapper.setDefaultTyping(typeResolverBuilder);
}
 
Example 5
Source File: EntityFormatter.java    From FROST-Server with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper();
    mapper.enable(SerializationFeature.INDENT_OUTPUT);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.setPropertyNamingStrategy(new EntitySetCamelCaseNamingStrategy());

    MixinUtils.addMixins(mapper);

    SimpleModule module = new SimpleModule();
    GeoJsonSerializer geoJsonSerializer = new GeoJsonSerializer();
    for (String encodingType : GeoJsonDeserializier.ENCODINGS) {
        CustomSerializationManager.getInstance().registerSerializer(encodingType, geoJsonSerializer);
    }

    module.addSerializer(Entity.class, new EntitySerializer());
    module.addSerializer(EntitySetResult.class, new EntitySetResultSerializer());
    module.addSerializer(TimeValue.class, new TimeValueSerializer());
    mapper.registerModule(module);
    return mapper;
}
 
Example 6
Source File: HuobiApiClient.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
static ObjectMapper createObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
    mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    // disabled features:
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    return mapper;
}
 
Example 7
Source File: JsonDocumentSearchResponseUnmarshaller.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
public JsonDocumentSearchResponseUnmarshaller() {
    mapper = new ObjectMapper();
    mapper.registerModule(new JodaModule());
    mapper.configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true);
    mapper.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
    mapper.setPropertyNamingStrategy(new LowerCasePropertyNamingStrategy());
}
 
Example 8
Source File: JacksonProvider.java    From minnal with Apache License 2.0 5 votes vote down vote up
/**
 * @param mapper
 * @param annotationsToUse
 */
public JacksonProvider(ObjectMapper mapper, Annotations[] annotationsToUse) {
	super(mapper, annotationsToUse);
	mapper.setVisibility(PropertyAccessor.FIELD, Visibility.NONE);
	mapper.setVisibility(PropertyAccessor.GETTER, Visibility.PROTECTED_AND_PUBLIC);
	mapper.setVisibility(PropertyAccessor.SETTER, Visibility.PROTECTED_AND_PUBLIC);
	mapper.configure(MapperFeature.REQUIRE_SETTERS_FOR_GETTERS, true);
	mapper.setPropertyNamingStrategy(getPropertyNamingStrategy());
}
 
Example 9
Source File: JsonApiHttpMessageConverter.java    From JuniperBot with GNU General Public License v3.0 5 votes vote down vote up
public JsonApiHttpMessageConverter(Class<?>... classes) {
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    objectMapper.configure(com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    this.converter = new ResourceConverter(classes);
    this.converter.enableDeserializationOption(DeserializationFeature.ALLOW_UNKNOWN_INCLUSIONS);
}
 
Example 10
Source File: JsonDocumentUpdateMarshaller.java    From Cheddar with Apache License 2.0 5 votes vote down vote up
private JsonDocumentUpdateMarshaller() {
    mapper = new ObjectMapper();
    final SimpleModule module = new SimpleModule();
    module.addSerializer(Boolean.class, new BooleanLiteralSerializer());
    mapper.registerModule(module);
    mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    mapper.registerModule(new JodaModule());
    mapper.setPropertyNamingStrategy(new LowerCasePropertyNamingStrategy());
}
 
Example 11
Source File: Jackson.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createMapper() {
  ObjectMapper mapper = new ObjectMapper();
  mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
  mapper.findAndRegisterModules();
  SimpleModule module = new SimpleModule();
  mapper.registerModule(module);
  mapper.enable(SerializationFeature.INDENT_OUTPUT);
  mapper.setSerializationInclusion(Include.NON_NULL);
  return mapper;
}
 
Example 12
Source File: Jackson.java    From metanome-algorithms with Apache License 2.0 5 votes vote down vote up
private static ObjectMapper createMapper() {
	ObjectMapper mapper = new ObjectMapper();
	mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
	mapper.findAndRegisterModules();
	SimpleModule module = new SimpleModule();
	mapper.registerModule(module);
	mapper.enable(SerializationFeature.INDENT_OUTPUT);
	mapper.enable(MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS);
	mapper.setSerializationInclusion(Include.NON_NULL);
	return mapper;
}
 
Example 13
Source File: TestCaseValidationSpringConfig.java    From backstopper with Apache License 2.0 5 votes vote down vote up
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.clear();
    converters.add(new ByteArrayHttpMessageConverter());
    converters.add(new StringHttpMessageConverter());
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    final ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.CAMEL_CASE_TO_LOWER_CASE_WITH_UNDERSCORES);
    converter.setObjectMapper(objectMapper);
    converters.add(converter);
    super.configureMessageConverters(converters);
}
 
Example 14
Source File: HuobiApiClient.java    From zheshiyigeniubidexiangmu with MIT License 5 votes vote down vote up
static ObjectMapper createObjectMapper() {
    final ObjectMapper mapper = new ObjectMapper();
    mapper.setPropertyNamingStrategy(PropertyNamingStrategy.KEBAB_CASE);
    mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
    // disabled features:
    mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    mapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
    return mapper;
}
 
Example 15
Source File: SubtypeModuleTests.java    From spring-cloud-bus with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeserializeCustomizedObjectMapper() throws Exception {
	ObjectMapper mapper = new ObjectMapper();
	mapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);

	BusJacksonMessageConverter converter = new BusJacksonMessageConverter(mapper);
	converter.afterPropertiesSet();
	Object event = converter.fromMessage(MessageBuilder.withPayload(
			"{\"type\":\"TestRemoteApplicationEvent\", \"origin_service\":\"myorigin\"}")
			.build(), RemoteApplicationEvent.class);
	assertThat(event).isNotNull().isInstanceOf(TestRemoteApplicationEvent.class);
	assertThat(TestRemoteApplicationEvent.class.cast(event).getOriginService())
			.isEqualTo("myorigin");
}
 
Example 16
Source File: JsonUtils.java    From halo with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates a default json mapper.
 *
 * @param strategy property naming strategy
 * @return object mapper
 */
@NonNull
public static ObjectMapper createDefaultJsonMapper(@Nullable PropertyNamingStrategy strategy) {
    // Create object mapper
    ObjectMapper mapper = new ObjectMapper();
    // Configure
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    // Set property naming strategy
    if (strategy != null) {
        mapper.setPropertyNamingStrategy(strategy);
    }
    return mapper;
}
 
Example 17
Source File: SpecificationLoader.java    From aws-cloudformation-template-schema with Apache License 2.0 5 votes vote down vote up
public SpecificationLoader() {
    jsonFactory = new MappingJsonFactory();
    mapperForJSON = new ObjectMapper(jsonFactory);
    mapperForJSON.configure(MapperFeature.USE_STD_BEAN_NAMING, true)
        .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
        .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false)
        .configure(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES, true)
        .configure(SerializationFeature.FAIL_ON_SELF_REFERENCES, true)
        .configure(SerializationFeature.WRITE_SINGLE_ELEM_ARRAYS_UNWRAPPED, true)
        .configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
        .setSerializationInclusion(JsonInclude.Include.NON_EMPTY);
    jsonFactory.setCodec(mapperForJSON);
    mapperForJSON.setPropertyNamingStrategy(PropertyNamingStrategy.UPPER_CAMEL_CASE);
}
 
Example 18
Source File: JsonDataformatsRoute.java    From camel-quarkus with Apache License 2.0 4 votes vote down vote up
@Override
public void configure() {
    JacksonDataFormat jacksonDummyObjectDataFormat = new JacksonDataFormat(DummyObject.class);
    jacksonDummyObjectDataFormat.useList();
    ObjectMapper jacksonObjectMapper = new ObjectMapper();
    jacksonObjectMapper.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    jacksonDummyObjectDataFormat.setObjectMapper(jacksonObjectMapper);
    configureJsonRoutes(JsonLibrary.Jackson, jacksonDummyObjectDataFormat, new JacksonDataFormat(PojoA.class),
            new JacksonDataFormat(PojoB.class));

    JohnzonDataFormat johnzonDummyObjectDataFormat = new JohnzonDataFormat();
    johnzonDummyObjectDataFormat.setParameterizedType(new JohnzonParameterizedType(List.class, DummyObject.class));
    configureJsonRoutes(JsonLibrary.Johnzon, johnzonDummyObjectDataFormat, new JohnzonDataFormat(PojoA.class),
            new JohnzonDataFormat(PojoB.class));

    GsonDataFormat gsonDummyObjectDataFormat = new GsonDataFormat();
    Type genericType = new TypeToken<List<DummyObject>>() {
    }.getType();
    gsonDummyObjectDataFormat.setUnmarshalGenericType(genericType);
    gsonDummyObjectDataFormat.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES);
    gsonDummyObjectDataFormat.setExclusionStrategies(Arrays.<ExclusionStrategy> asList(new ExclusionStrategy() {
        @Override
        public boolean shouldSkipField(FieldAttributes f) {
            return f.getAnnotation(ExcludeField.class) != null;
        }

        @Override
        public boolean shouldSkipClass(Class<?> clazz) {
            return false;
        }
    }));
    configureJsonRoutes(JsonLibrary.Gson, gsonDummyObjectDataFormat, new GsonDataFormat(PojoA.class),
            new GsonDataFormat(PojoB.class));

    from("direct:jacksonxml-marshal")
            .marshal()
            .jacksonxml(true);

    from("direct:jacksonxml-unmarshal")
            .unmarshal()
            .jacksonxml(PojoA.class);

}
 
Example 19
Source File: FcoinOrderService.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
@Override
public OrderBean getOrder(String ak, String sk, String symbol, String order_id) {
    try {
        ObjectMapper mapper = new ObjectMapper();
        mapper.setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE);
        String uri = "https://api.fcoin.com/v2/orders/" + order_id;
        Long ts = System.currentTimeMillis();
        String sign = SignUtil.fcoinSign(ak,sk,"GET", uri, null, ts);
        Map<String, String> headers = new HashMap<>();
        headers.put("FC-ACCESS-KEY",ak);
        headers.put("FC-ACCESS-SIGNATURE",sign);
        headers.put("FC-ACCESS-TIMESTAMP",ts.toString());
        String json = this.get(uri, headers);
        FcoinOrderResponse res = mapper.readValue(json, FcoinOrderResponse.class);
        if (res!=null && res.getStatus()==0 && res.getData()!=null) {
            FcoinOrder order = res.getData();
            OrderBean orderBean = new OrderBean();
            orderBean.setAmount(order.getAmount());
            orderBean.setOrder_id(order.getId());
            orderBean.setPrice(order.getPrice());
            orderBean.setSymbol(order.getSymbol());
            orderBean.setType(order.getSide());
            if (order.getState().equals("submitted")) {
                orderBean.setStatus(df.format(0));
            } else if (order.getState().equals("canceled")) {
                orderBean.setStatus(df.format(-1));
            } else if (order.getState().equals("filled")) {
                orderBean.setStatus(df.format(2));
            } else if (order.getState().equals("partial_filled") || order.getState().equals("partial_canceled")) {
                orderBean.setStatus(df.format(1));
            } else if (order.getState().equals("pending_cancel")) {  // 失效
                orderBean.setStatus(df.format(4));
            }
            orderBean.setField_amount(order.getFilled_amount());
            return orderBean;
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}
 
Example 20
Source File: FcoinOrderService.java    From zheshiyigeniubidexiangmu with MIT License 4 votes vote down vote up
/**
     * symbol		交易对
     states		订单状态
     before		查询某个页码之前的订单
     after		查询某个页码之后的订单
     limit		每页的订单数量,默认为 20 条
     * @param ak
     * @param sk
     * @param symbol
     * @return
     */
    @Override
    public List<OrderBean> getAllOrder(String ak, String sk, String symbol) {
        // GET https://api.fcoin.com/v2/orders
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.setPropertyNamingStrategy(PropertyNamingStrategy.PASCAL_CASE_TO_CAMEL_CASE);
            String uri = "https://api.fcoin.com/v2/orders?states=submitted&symbol="+symbol;
            Long ts = System.currentTimeMillis();
//            Map<String, String> map = new HashMap<>();
//            map.put("symbio", symbol);
            String sign = SignUtil.fcoinSign(ak,sk,"GET", uri, null, ts);
            Map<String, String> headers = new HashMap<>();
            headers.put("FC-ACCESS-KEY",ak);
            headers.put("FC-ACCESS-SIGNATURE",sign);
            headers.put("FC-ACCESS-TIMESTAMP",ts.toString());
            String json = this.get(uri, headers);
            FcoinOrderListResponse res = mapper.readValue(json, FcoinOrderListResponse.class);
            if (res!=null && res.getStatus()==0 && res.getData()!=null) {
                List<OrderBean> list = new ArrayList<>();
                for (FcoinOrder order:res.getData()) {
                    OrderBean orderBean = new OrderBean();
                    orderBean.setAmount(order.getAmount());
                    orderBean.setOrder_id(order.getId());
                    orderBean.setPrice(order.getPrice());
                    orderBean.setSymbol(order.getSymbol());
                    orderBean.setType(order.getSide());
                    if (order.getState().equals("submitted")) {
                        orderBean.setStatus(df.format(0));
                    } else if (order.getState().equals("canceled")) {
                        orderBean.setStatus(df.format(-1));
                    } else if (order.getState().equals("filled")) {
                        orderBean.setStatus(df.format(2));
                    } else if (order.getState().equals("partial_filled") || order.getState().equals("partial_canceled")) {
                        orderBean.setStatus(df.format(1));
                    } else if (order.getState().equals("pending_cancel")) {  // 失效
                        orderBean.setStatus(df.format(4));
                    }
                    orderBean.setField_amount(order.getFilled_amount());
                    list.add(orderBean);
                }
                return list;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }