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.