下面列出了com.fasterxml.jackson.databind.ObjectMapper#setPropertyNamingStrategy ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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);
}
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);
}
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;
}
/**
* 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);
}
/**
* 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);
}
}
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);
}
/**
* 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;
}
@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");
}
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;
}
@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);
}
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;
}
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;
}
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;
}
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());
}
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);
}
/**
* @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());
}
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());
}
@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);
}
/**
* 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;
}
}
@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;
}
}