Quantcast
Channel: Mkyong.com
Viewing all articles
Browse latest Browse all 28

Gson supports Java 8 date time types

$
0
0

Gson does not directly support Java 8’s date-time APIs like LocalDate, LocalDateTime, and ZonedDateTime. However, we can create a custom JSON serializer to support Java 8 date-time types.

This article shows how to use Gson to handle the LocalDate type.

Table of contents:

P.S Tested with Gson 2.10.1

1. Setup Google Gson

Declares gson in the pom.xml.

pom.xml

    <dependency>
        <groupId>com.google.code.gson</groupId>
        <artifactId>gson</artifactId>
        <version>2.10.1</version>
    </dependency>

2. Default, Gson does not support Java 8 date-time type

By default, when we use Gson to handle Java 8 date-time type like LocalDate, it will hit the Java 9 module error.

Book

package com.mkyong.json.model;

import java.math.BigDecimal;
import java.time.LocalDate;

public class Book {
    private Long id;
    private String title;
    private BigDecimal price;

    private LocalDate publishDate; // Java 8 date-time apis

    // getters, setters, constructors and etc
}

    Gson gson = new Gson();

    Book book =
        new Book(1L, "Book A", BigDecimal.valueOf(9.99),LocalDate.of(2023, 10, 1));

    String json = gson.toJson(book); // Serialize

Caused by: java.lang.reflect.InaccessibleObjectException: Unable to make field private final int java.time.LocalDate.year accessible: module java.base does not "opens java.time" to unnamed module @57fa26b7
	at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
	at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
	at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
	at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
	at com.google.gson.internal.reflect.ReflectionHelper.makeAccessible(ReflectionHelper.java:35)
	... 12 more

3. Custom Serializer and Deserializer for LocalDate

In Gson, to handle LocalDate, we must create a custom serializer and deserializer for the LocalDate type.

3.1 A custom JSON Serializer and Deserializer for the LocalDate type.

LocalDateAdapter.java

package com.mkyong.json.gson.java8date;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateAdapter implements JsonSerializer<LocalDate>, JsonDeserializer<LocalDate> {

    private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;

    @Override
    public JsonElement serialize(LocalDate localDate,
                                 Type type,
                                 JsonSerializationContext jsonSerializationContext) {

        return new JsonPrimitive(localDate.format(formatter)); // "yyyy-MM-dd"

    }

    @Override
    public LocalDate deserialize(JsonElement jsonElement,
                                 Type type,
                                 JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {

        return LocalDate.parse(jsonElement.getAsJsonPrimitive().getAsString(), formatter);
    }

}

3.2 Register the above LocalDateAdapter via GsonBuilder. Now, we can use Gson to handle the LocalDate.

GsonJava8TimeExample.java

package com.mkyong.json.gson.java8date;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.mkyong.json.model.Book;

import java.math.BigDecimal;
import java.time.LocalDate;

public class GsonJava8TimeExample {

    public static void main(String[] args) {

        Gson gson = new GsonBuilder()
                // register custom JsonSerializer for LocalDate
                .registerTypeAdapter(LocalDate.class, new LocalDateAdapter())
                .create();

        Book book =
                new Book(1L, "Book A",
                        BigDecimal.valueOf(9.99),
                        LocalDate.of(2023, 10, 1));

        String json = gson.toJson(book); // Serialize
        System.out.println("Serialized book: " + json);

        Book newBook = gson.fromJson(json, Book.class);// Deserialize
        System.out.println("Deserialized book: " + newBook);


    }
}

Output


Serialized book: {"id":1,"title":"Book A","price":9.99,"publishDate":"2023-10-01"}
Deserialized book: Book{id=1, title='Book A', price=9.99, publishDate=2023-10-01}

Note
We can create similar adapters for other Java 8 date-time types, such as LocalDateTime, ZonedDateTime, or OffsetDateTime.

4. Download Source Code

$ git clone https://github.com/mkyong/java-json

$ cd gson

5. References

The post Gson supports Java 8 date time types appeared first on Mkyong.com.


Viewing all articles
Browse latest Browse all 28

Trending Articles