|
| 1 | +package com.retailsvc.http; |
| 2 | + |
| 3 | +import com.google.gson.Gson; |
| 4 | +import com.google.gson.GsonBuilder; |
| 5 | +import com.retailsvc.http.internal.gson.GsonJsonMapper; |
| 6 | +import java.util.Objects; |
| 7 | + |
| 8 | +/** |
| 9 | + * {@link TypeMapper} for {@code application/json} backed by Gson. Mirrors the ergonomics of {@link |
| 10 | + * Jackson2JsonTypeMapper} / {@link Jackson3JsonTypeMapper}: the caller supplies a fully configured |
| 11 | + * {@link Gson}; this class never silently mutates it. |
| 12 | + * |
| 13 | + * <p>The no-argument constructor uses the library's default {@link Gson} — the same JSR-310-aware |
| 14 | + * instance the built-in auto-registration produces — making this a drop-in replacement for the |
| 15 | + * auto-registered mapper when callers want to wire it explicitly. |
| 16 | + * |
| 17 | + * <p>To extend the library default with extra type adapters or settings, use {@link |
| 18 | + * #gsonBuilder()}: |
| 19 | + * |
| 20 | + * <pre>{@code |
| 21 | + * Gson custom = |
| 22 | + * new GsonTypeMapper() |
| 23 | + * .gsonBuilder() |
| 24 | + * .registerTypeAdapter(MyType.class, new MyTypeAdapter()) |
| 25 | + * .create(); |
| 26 | + * new GsonTypeMapper(custom); |
| 27 | + * }</pre> |
| 28 | + */ |
| 29 | +public final class GsonTypeMapper implements TypedTypeMapper { |
| 30 | + |
| 31 | + private final GsonJsonMapper delegate; |
| 32 | + |
| 33 | + /** Creates a mapper backed by the library's default JSR-310-aware {@link Gson}. */ |
| 34 | + public GsonTypeMapper() { |
| 35 | + this.delegate = new GsonJsonMapper(); |
| 36 | + } |
| 37 | + |
| 38 | + /** |
| 39 | + * Creates a mapper backed by the supplied {@link Gson}. |
| 40 | + * |
| 41 | + * @throws NullPointerException if {@code gson} is null |
| 42 | + */ |
| 43 | + public GsonTypeMapper(Gson gson) { |
| 44 | + this.delegate = new GsonJsonMapper(Objects.requireNonNull(gson, "gson must not be null")); |
| 45 | + } |
| 46 | + |
| 47 | + /** |
| 48 | + * Returns a {@link GsonBuilder} pre-populated with the wrapped {@link Gson}'s configuration, so |
| 49 | + * callers can derive a customized {@link Gson} from the library default (or from their own |
| 50 | + * starting point). |
| 51 | + */ |
| 52 | + public GsonBuilder gsonBuilder() { |
| 53 | + return delegate.gson().newBuilder(); |
| 54 | + } |
| 55 | + |
| 56 | + @Override |
| 57 | + public Object readFrom(byte[] body, String contentTypeHeader) { |
| 58 | + return delegate.readFrom(body, contentTypeHeader); |
| 59 | + } |
| 60 | + |
| 61 | + @Override |
| 62 | + public <T> T readAs(byte[] body, String contentTypeHeader, Class<T> type) { |
| 63 | + return delegate.readAs(body, contentTypeHeader, type); |
| 64 | + } |
| 65 | + |
| 66 | + @Override |
| 67 | + public byte[] writeTo(Object value) { |
| 68 | + return delegate.writeTo(value); |
| 69 | + } |
| 70 | +} |
0 commit comments