强制Jackson将LocalDate序列化为数组 [英] Force Jackson serialize LocalDate to Array
问题描述
我正在使用spring-boot 2.1.6,并且有一个API可以接受包含日期的表单,例如:
I'm using spring-boot 2.1.6 and there is an API to accept a form including a date like:
@Data
public class MyForm {
private LocalDate date;
...
}
@Controller
public class MyController {
@PostMapping("...")
public ResponseEntity<...> post(@RequestBody MyForm myForm) {
...
}
}
默认情况下,spring MVC接受以下JSON格式:
By default spring MVC accept this JSON format:
{
"date": [2020, 6, 17],
...
}
因此在前端,我的JavaScript代码只需提交这样的表单,即JS会将日期转换为数组.
So in Front-End, my JavaScript code just submit a form like this, i.e. JS will convert a date to an array.
但是当我运行spring-boot测试时,使用以下代码,此序列化将不起作用:
But when I run spring-boot test, this serialization does not work, with the following code:
private ObjectMapper mapper = new ObjectMapper();
@Autowired
private MockMvc mockMvc;
@Test
public void doTest() {
MyForm form = ...
MvcResult result = mockMvc.perform(MockMvcRequestBuilders.post("/...").
contentType("application/json").content(mapper.writeValueAsString(form)).andReturn();
...
}
这是因为杰克逊默认情况下将LocalDate序列化为:
This is because Jackson by default serialize LocalDate as:
{
"date": {
"year":2020,
"month":"JUNE",
"monthValue":6,
...
}
...
}
如此处所述: LocalDate序列化:日期是否为数组?,有很多强制spring-boot将数据序列化为格式yyyy-MM-dd
的配置.但是我不想更改我的JS代码.我只是想让我的测试用例工作.
As mentioned here: LocalDate Serialization: date as array? , there are many configurations to force spring-boot serialize data as format yyyy-MM-dd
. But I don't want to change my JS code. I just want to make my test case work.
如何配置ObjectMapper
以强制Jackson将LocalDate序列化为数组?我只想得到这个:
How can I configure ObjectMapper
to force Jackson to serialize LocalDate to Array? I just want to get this:
{
"date": [2020, 6, 17],
...
}
更新
LocalDate
这里是java.time.LocalDate
,但不是org.joda.time.LocalDate
.
推荐答案
您需要注册JavaTimeModule
. Maven依赖项:
You need to register JavaTimeModule
. Maven dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
示例,如何使用它:
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import java.time.LocalDate;
public class JsonApp {
public static void main(String[] args) throws Exception {
JsonMapper mapper = JsonMapper.builder()
.addModule(new JavaTimeModule())
.build();
mapper.writeValue(System.out, new MyForm());
}
}
class MyForm {
private LocalDate value = LocalDate.now();
public LocalDate getValue() {
return value;
}
public void setValue(LocalDate value) {
this.value = value;
}
}
上面的代码显示:
{"value":[2020,6,17]}
另请参阅:
- jackson-modules-java8
- Jackson Serialize Instant to Nanosecond Issue
- Jackson deserialize elasticsearch long as LocalDateTime with Java 8
这篇关于强制Jackson将LocalDate序列化为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!