在 Spring JMS 消息中配置 JSON 输出

sch*_*los 3 java spring-jms spring-boot jackson2

我想要什么

在 Spring Boot 1.5.2 项目中,我通过JmsTemplate#convertAndSend将 JSON 消息发送到一些 JMS (ActiveMQ) 队列/主题。我使用Java 8中的一些实例LocalDateLocalDateTime。我想稍微更改 JSON 输出:

  • 漂亮地打印 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" } }
Run Code Online (Sandbox Code Playgroud)

我试过的

我已经添加jackson-datatype-jsr310到项目依赖项中,并且我还设置了

spring.jackson.serialization.indent-output=true
spring.jackson.serialization.write_dates_as_timestamps=false
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

但行为仍然没有变化。

如何自定义 JSON 输出,如上所述?

sch*_*los 5

进一步配置对象映射器,如下所示:

    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);
Run Code Online (Sandbox Code Playgroud)

与这里的答案一致:https : //stackoverflow.com/a/41089874/72625