adam bien's blog

JSON-B: How to Serialize a Formatted LocalDateTime into JSON--and Back 📎

To serialize a LocalDateTime:

import java.time.LocalDateTime;

import jakarta.json.bind.annotation.JsonbDateFormat;

public class DateAndTime {

    @JsonbDateFormat("dd/MM/yyyy HH:mm:ss.SSS") //optional
    public LocalDateTime dateAndTime;

    @Override
    public String toString() {
        return "DateAndTime [dateAndTime=" + dateAndTime + "]";
    }
}
    

into JSON and read it back with Jakarta JSON Binding (JSON-B), add the following dependency to your pom.xml:


<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>2.0.4</version>
</dependency>

Now the DateAndTime class can be serialized into a String and deserialized back into another DateAndTime instance:


import java.time.LocalDateTime;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import jakarta.json.bind.Jsonb;
import jakarta.json.bind.JsonbBuilder;

public class DateAndTimeTest {

    private Jsonb jsonb;
    
    @BeforeEach
    public void init() {
        this.jsonb = JsonbBuilder.newBuilder().build();
    }

    @Test
    public void dates(){
        var dateAndTime = new DateAndTime();
        dateAndTime.dateAndTime = LocalDateTime.now();
        var serialized = this.jsonb.toJson(dateAndTime);
        System.out.println(serialized);
        System.out.println("---");
        
        var deserialized = this.jsonb.fromJson(serialized, DateAndTime.class);
        System.out.println(deserialized);
    }
}

Output:


{"dateAndTime":"29.01.2022 16:07:15"}
---
DateAndTime [dateAndTime=2022-01-29T16:07:15]