Google Auto Value with Jackson Json

 I got a chance to work on a code base which used Google's Auto Value library and Jackson library for serialising and deserialising Json request and response payload. I tried to get the sweet spot with minimal need of annotations from Auto Value and Jackson. The following example shows the bare minimal change need to generate Json payload. It has the flexibility to construct the value object using builder pattern and ability to handle optional fields, collections and change the field name if required.


package com.harishkannarao.example;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonPOJOBuilder;
import com.google.auto.value.AutoValue;

import java.time.OffsetDateTime;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

@AutoValue
@JsonDeserialize(builder = AutoValue_ExampleModel.Builder.class)
public abstract class ExampleModel {

    public abstract UUID getId();
    public abstract Optional<String> getTitle();
    public abstract String getName();
    public abstract OffsetDateTime getDateTime();
    @JsonProperty("long")
    public abstract Optional<Long> getLongField();
    public abstract boolean isEligible();
    public abstract List<String> getFavouritePlaces();

    public abstract Builder toBuilder();

    public static Builder builder() {
        return new AutoValue_ExampleModel.Builder();
    }

    @SuppressWarnings("OptionalUsedAsFieldOrParameterType")
    @AutoValue.Builder
    @JsonPOJOBuilder(withPrefix = "")
    public static abstract class Builder {
        public abstract Builder id(UUID value);
        public abstract Builder title(Optional<String> value);
        public abstract Builder name(String value);
        public abstract Builder dateTime(OffsetDateTime value);
        @JsonProperty("long")
        public abstract Builder longField(Optional<Long> value);
        public abstract Builder eligible(boolean value);
        public abstract Builder favouritePlaces(List<String> values);
        public abstract ExampleModel build();
    }
}

Comments

Popular posts from this blog

JSON with curl and jq

Import self signed in Linux for Chrome / Chromium headless testing

Colima - Drop In replacement for Docker Desktop for Mac and Linux