Serialize Java LocalDate as yyyy-mm-dd with Gson

Serialize Java LocalDate as yyyy-mm-dd with Gson

To serialize a Java LocalDate as yyyy-mm-dd format with Gson (Google's JSON serialization/deserialization library), you can create a custom JsonSerializer for LocalDate. Here's how you can do it:

  • First, make sure you have Gson added as a dependency in your project's build file (e.g., build.gradle or pom.xml).

  • Create a custom JsonSerializer for LocalDate:

import com.google.gson.JsonElement; import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; import java.time.LocalDate; import java.time.format.DateTimeFormatter; public class LocalDateSerializer implements JsonSerializer<LocalDate> { private final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd"); @Override public JsonElement serialize(LocalDate localDate, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(formatter.format(localDate)); } } 

In this code:

  • We create a LocalDateSerializer class that implements Gson's JsonSerializer interface for LocalDate.

  • In the serialize method, we format the LocalDate as a String in the "yyyy-MM-dd" pattern using DateTimeFormatter, and then wrap it in a JsonPrimitive for serialization.

  • Register the custom serializer with Gson:
import com.google.gson.Gson; import com.google.gson.GsonBuilder; import java.time.LocalDate; public class Main { public static void main(String[] args) { // Create Gson instance with the custom serializer Gson gson = new GsonBuilder() .registerTypeAdapter(LocalDate.class, new LocalDateSerializer()) .create(); // Serialize a LocalDate object LocalDate date = LocalDate.now(); String json = gson.toJson(date); System.out.println(json); } } 

In the Main class, we create a Gson instance and register the LocalDateSerializer as a type adapter using registerTypeAdapter. Then, we serialize a LocalDate object using Gson, which will format it in the "yyyy-MM-dd" pattern.

When you run this code, you will get a JSON representation of the LocalDate object in the desired format:

"2023-11-30" 

This custom serializer allows you to control how LocalDate objects are serialized to JSON while using Gson.


More Tags

percentage coturn swift io hadoop-partitioning indexoutofrangeexception anomaly-detection marshalling android-pendingintent data.table

More Java Questions

More Statistics Calculators

More Bio laboratory Calculators

More Entertainment Anecdotes Calculators

More Stoichiometry Calculators