Skip to content

Custom Types and Serializers

Custom serializers allow you to represent more complex data structures in your analytics. The Hoglin SDK uses Gson for serialization, so you can register an adapter very similar to a typical Gson TypeAdapter. There are two methods of doing this:


We provide HoglinAdapter, a type you can extend to create your own custom serializer. HoglinAdapter is a simple wrapper around Gson’s TypeAdapter but also allows for automatic registration in the SDK’s Gson instance through Google AutoService.

HoglinAdapter for serializing Instant objects - this is already bundled in the SDK as it’s used internally, meaning the Instant type will be serializable when tracking your events:

@AutoService(HoglinAdapter.class)
public class InstantSerializer extends HoglinAdapter<Instant> {
@Override
public void write(final JsonWriter out, final Instant value) throws IOException {
if (value == null) {
out.nullValue();
} else {
out.value(value.toString());
}
}
@Override
public Instant read(final JsonReader reader) throws IOException {
if (reader.peek() == JsonToken.NULL) {
reader.nextNull();
return null;
}
return Instant.parse(reader.nextString());
}
@Override
public Class<?> getType() {
return Instant.class;
}
}

There’s no need for manual registration of this adapter, the @AutoService annotation will allow for the SDK to automatically register it behind the scenes.


You may alternatively choose to use your own Gson instance instead of the one provided by the SDK. This way, you can register custom serializers directly with it. This is useful if you already intend to use Gson to serialize the same types for another purpose, or if for any other reason you would like more control over serialization in the SDK. A custom Gson instance can be passed into the Hoglin builder:

final Gson gson = new GsonBuilder()
.registerTypeAdapter(Instant.class, new InstantSerializer()) // Assuming we've already made this InstantSerializer class
.create();
final Hoglin hoglin = new Hoglin.Builder("api_key")
.gson(gson) // Pass in your custom Gson instance
.create()