Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Force Jackson serialize LocalDate to Array

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) {
        ...
    }
}

By default spring MVC accept this JSON format:

{
   "date": [2020, 6, 17],
   ...
}

So in Front-End, my JavaScript code just submit a form like this, i.e. JS will convert a date to an array.

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();
        ...
    }

This is because Jackson by default serialize LocalDate as:

{
    "date": {
        "year":2020,
        "month":"JUNE",
        "monthValue":6,
        ...
    }
    ...
}

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.

How can I configure ObjectMapper to force Jackson to serialize LocalDate to Array? I just want to get this:

{
   "date": [2020, 6, 17],
   ...
}

UPDATE

LocalDate here is java.time.LocalDate but not org.joda.time.LocalDate.

like image 422
auntyellow Avatar asked Oct 15 '22 02:10

auntyellow


1 Answers

You need to register JavaTimeModule. Maven dependency:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

Example, how to use it:

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;
    }
}

Above code prints:

{"value":[2020,6,17]}

See also:

  • jackson-modules-java8
  • Jackson Serialize Instant to Nanosecond Issue
  • Jackson deserialize elasticsearch long as LocalDateTime with Java 8
like image 79
Michał Ziober Avatar answered Oct 31 '22 10:10

Michał Ziober