Client and backend. This class is shared: the same code is compiled into your app and into your server, so everything on this page works in both.

@Retention(CLASS) @Target({TYPE, FIELD})

public @interface JsonAdapter

Hands a type’s JSON form to the application’s own JsonTypeAdapter.

On a field it applies to that field; on a class, to every field, element and body of that class, which is how a type the generated codecs cannot map – a money value, an identifier wrapper – gets one form everywhere. A field’s adapter wins over its class’s.

public final class EpochSecondsAdapter implements JsonTypeAdapter<java.util.Date> {
    public Object toJson(java.util.Date d) {
        return d == null ? null : Long.valueOf(d.getTime() / 1000);
    }
    public java.util.Date fromJson(Object json) {
        if (json == null) {
            return null;
        }
        // instanceof, never a bare cast: a failed cast does not throw on iOS.
        if (!(json instanceof Number)) {
            throw new IllegalArgumentException("expected epoch seconds");
        }
        return new java.util.Date(((Number) json).longValue() * 1000);
    }
}

@Mapped
public class Invoice {
    @JsonAdapter(EpochSecondsAdapter.class)
    public java.util.Date issued;
}

The adapter needs a public constructor without arguments. The generated code creates one instance per adapter class and calls it directly, so nothing is found by name at run time and the translated binary keeps the class.

Methods

public abstract Class<? extends JsonTypeAdapter> value()The adapter class.

Method details

value

public abstract Class<? extends JsonTypeAdapter> value()
The adapter class.