【问题标题】:Configure JSON output in Spring JMS messages在 Spring JMS 消息中配置 JSON 输出
【发布时间】:2017-07-29 21:20:07
【问题描述】:

我想要什么

在 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" } }

我尝试过的

我已将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 输出?

【问题讨论】:

    标签: java spring-boot spring-jms jackson2


    【解决方案1】:

    像这样进一步配置对象映射器:

        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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-20
      • 2022-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-31
      • 1970-01-01
      相关资源
      最近更新 更多