我正在使用 fastxml 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 等效字符串不会转换为 JSON,如上所述 here .
@RestController
public class SampleController {
@RequestMapping(value = "/jsonInfo", method = RequestMethod.GET, produces = APPLICATION_JSON_VALUE)
public String jsonInfo() {
String string = "{\"name\": \"foo\"}"
return string;
}
}
最佳答案
试试这个
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);
}
}
关于java - Spring Boot Jackson 映射不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38831081/