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;

    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:


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;
    public void init() {
        this.jsonb = JsonbBuilder.newBuilder().build();

    public void dates(){
        var dateAndTime = new DateAndTime();
        dateAndTime.dateAndTime = LocalDateTime.now();
        var serialized = this.jsonb.toJson(dateAndTime);
        var deserialized = this.jsonb.fromJson(serialized, DateAndTime.class);


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


Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments