How do you create a custom serializer in GSON?

How do you create a custom serializer in GSON?

A) By implementing the JsonSerializer interface
B) By overriding the toString() method
C) By using the @SerializedName annotation
D) By setting a flag in the GsonBuilder

Answer:

A) By implementing the JsonSerializer interface

Explanation:

In GSON, you can create a custom serializer by implementing the JsonSerializer interface. This allows you to define how a particular type of object should be serialized to JSON, using your own logic.

For example:


public class CustomDateSerializer implements JsonSerializer<Date> {
    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(new SimpleDateFormat("yyyy-MM-dd").format(src));
    }
}

Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new CustomDateSerializer()).create();
String json = gson.toJson(new Date());

In this example, the CustomDateSerializer class implements the JsonSerializer interface to format dates as “yyyy-MM-dd” in the JSON output. The serializer is registered with GSON using the registerTypeAdapter method.

Reference links:

https://www.javaguides.net/p/top-java-libraries.html

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top