2017-03-09 158 views
1

配置JSON輸出我想

在春季啓動1.5.2什麼項目,我通過JmsTemplate#convertAndSend發送JSON消息,一些JMS(ActiveMQ的)隊列/主題。我使用Java 8,其中一些實例爲LocalDateLocalDateTime。我想稍微改變JSON輸出:在Spring JMS消息

  • pretty-print the JSON;和
  • 以ISO格式呈現日期/時間戳。

默認情況下,JSON最終都在一個行,日期/時間戳轉換爲派出格式,例如:

"startDate" : { "year" : 2017, "month" : "MARCH", "era" : "CE", "dayOfYear" : 64, "dayOfWeek" : "SUNDAY", "leapYear" : false, "dayOfMonth" : 5, "monthValue" : 3, "chronology" : { "calendarType" : "iso8601", "id" : "ISO" } } 

我已經試過

我已經添加了jackson-datatype-jsr310到項目依賴我還設置

spring.jackson.serialization.indent-output=true 
spring.jackson.serialization.write_dates_as_timestamps=false 

application.properties。行爲沒有變化。

我又試圖修改消息變換的初始化包括以下設置:

@Bean 
@Primary 
public MessageConverter jacksonJmsMessageConverter() { 
    MappingJackson2MessageConverter converter = new MappingJackson2MessageConverter(); 
    converter.setTargetType(MessageType.TEXT); 
    converter.setTypeIdPropertyName("_type"); 

    ObjectMapper objectMapper = new ObjectMapper(); 
    // default settings for MappingJackson2MessageConverter 
    objectMapper.configure(MapperFeature.DEFAULT_VIEW_INCLUSION, false); 
    objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); 
    // add settings I want 
    objectMapper.enable(SerializationFeature.INDENT_OUTPUT); 
    objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); 
    converter.setObjectMapper(objectMapper); 

    return converter; 
} 

但仍然有任何變化。

如何定製上述的JSON輸出?

回答

2

而且配置對象映射器,像這樣:在線路

JavaTimeModule timeModule = new JavaTimeModule(); 
    timeModule.addSerializer(LocalDate.class, 
     new LocalDateSerializer(DateTimeFormatter.ISO_LOCAL_DATE)); 
    timeModule.addSerializer(LocalDateTime.class, 
     new LocalDateTimeSerializer(DateTimeFormatter.ISO_LOCAL_DATE_TIME)); 
    objectMapper.registerModule(timeModule); 

這個答案在這裏:https://stackoverflow.com/a/41089874/72625