【问题标题】:Spring Boot Jackson mappings are not workingSpring Boot Jackson 映射不起作用
【发布时间】:2016-12-14 08:08:41
【问题描述】:

我正在使用 fasterxml jackson 进行 json 序列化。我已将日期序列化程序编写为

public class DateObjectSerializer extends JsonSerializer<Date> {
    public static final String DATE_FORMAT = "dd.MM.yyyy";

    @Override
    public void serialize(Date date, JsonGenerator jgen, SerializerProvider provider) throws IOException, JsonProcessingException {
        System.out.println("From DateObjectSerializer");
        SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
        String formattedDate = dateFormat.format(date);
        jgen.writeString(formattedDate);
    }
}

但它没有被调用。但是其他 Jackson 序列化器工作正常。

所以我在 application.yaml 中添加了以下配置

spring:
  jackson:
    serialization-inclusion: non_null
    date-format: dd.MM.yyyy

但它不起作用。

所以我在 SpringBootConfiguration 类中添加了这段代码。

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    final ObjectMapper objectMapper = new ObjectMapper();
    SimpleDateFormat dateFormat = new SimpleDateFormat(DATE_FORMAT);
    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false).setDateFormat(dateFormat);
    converter.setObjectMapper(objectMapper);
    converters.add(converter);
    super.configureMessageConverters(converters);
}

现在日期已正确序列化。但是现在有效的 JSON 等效字符串不会像 here 中提到的那样转换为 JSON。

@RestController
public class SampleController {

    @RequestMapping(value = "/jsonInfo", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
    public String jsonInfo() {
        String string = "{\"name\": \"foo\"}"
                return string;
    }
}

【问题讨论】:

  • 我认为 Spring boot 1.4.1 支持属性基础配置。所以有操作系统问题1
  • 是什么让你这么想?
  • 他们的文档。在 1.4.0 文档中,他们讨论了基于属性的配置。但在 1.4.1 文档中,他们谈到了 @JsonComponent 和基于属性的配置。
  • @JsonComponent 是 1.4 中的新内容,但与基于属性的配置无关。至少从 1.3.0 开始支持您使用的属性。如果您将一个说明问题的示例放在一起,就会更容易看到正在发生的事情。
  • 我已对问题进行了编辑以使其更加清晰。并删除了最后一个问题,因为我找到了原因,

标签: java spring-boot jackson


【解决方案1】:

试试这个

import com.fasterxml.jackson.databind.ObjectMapper;

:

@Autowired
private ObjectMapper objectMapper;

@RestController
public class SampleController {

    @RequestMapping(value = "/jsonInfo", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
    public JsonNode jsonInfo()  throws JsonProcessingException, IOException {
        String string = "{\"name\": \"foo\"}"
                return objectMapper.readTree(string);
    }
}

【讨论】:

  • 它解决了最后一部分谢谢。但是我也使用了 Jsonformat。但这看起来更干净。
猜你喜欢
  • 2015-11-01
  • 2021-06-24
  • 1970-01-01
  • 2018-10-02
  • 2017-08-08
  • 2018-12-18
  • 2021-11-19
  • 2017-08-12
  • 2013-10-13
相关资源
最近更新 更多