ObjectJsonAdapter(Moshi moshi) { this.moshi = moshi; this.listJsonAdapter = moshi.adapter(List.class); this.mapAdapter = moshi.adapter(Map.class); this.stringAdapter = moshi.adapter(String.class); this.doubleAdapter = moshi.adapter(Double.class); this.booleanAdapter = moshi.adapter(Boolean.class); }
@CheckReturnValue public <T> JsonAdapter<T> adapter(Type type, Class<? extends Annotation>... annotationTypes) { if (annotationTypes.length == 1) { return adapter(type, annotationTypes[0]); } Set<Annotation> annotations = new LinkedHashSet<>(annotationTypes.length); for (Class<? extends Annotation> annotationType : annotationTypes) { annotations.add(Types.createJsonQualifierImplementation(annotationType)); } return adapter(type, Collections.unmodifiableSet(annotations)); }
/** See https://api.slack.com/methods/rtm.start. */ public RtmStartResponse rtmStart(String accessToken) throws IOException { HttpUrl url = baseUrl.newBuilder("rtm.start") .addQueryParameter("token", accessToken) .build(); Request request = new Request.Builder() .url(url) .build(); Call call = httpClient.newCall(request); try (Response response = call.execute()) { JsonAdapter<RtmStartResponse> jsonAdapter = moshi.adapter(RtmStartResponse.class); return jsonAdapter.fromJson(response.body().source()); } }
@CheckReturnValue public <T> JsonAdapter<T> adapter(Type type, Class<? extends Annotation> annotationType) { if (annotationType == null) { throw new NullPointerException("annotationType == null"); } return adapter(type, Collections.singleton(Types.createJsonQualifierImplementation(annotationType))); }
/** See https://api.slack.com/methods/oauth.access. */ public OAuthSession exchangeCode(String code, HttpUrl redirectUrl) throws IOException { HttpUrl url = baseUrl.newBuilder("oauth.access") .addQueryParameter("client_id", clientId) .addQueryParameter("client_secret", clientSecret) .addQueryParameter("code", code) .addQueryParameter("redirect_uri", redirectUrl.toString()) .build(); Request request = new Request.Builder() .url(url) .build(); Call call = httpClient.newCall(request); try (Response response = call.execute()) { JsonAdapter<OAuthSession> jsonAdapter = moshi.adapter(OAuthSession.class); return jsonAdapter.fromJson(response.body().source()); } }
static <T> JsonAdapter<Set<T>> newLinkedHashSetAdapter(Type type, Moshi moshi) { Type elementType = Types.collectionElementType(type, Collection.class); JsonAdapter<T> elementAdapter = moshi.adapter(elementType); return new CollectionJsonAdapter<Set<T>, T>(elementAdapter) { @Override Set<T> newCollection() { return new LinkedHashSet<>(); } }; }
static <T> JsonAdapter<Collection<T>> newArrayListAdapter(Type type, Moshi moshi) { Type elementType = Types.collectionElementType(type, Collection.class); JsonAdapter<T> elementAdapter = moshi.adapter(elementType); return new CollectionJsonAdapter<Collection<T>, T>(elementAdapter) { @Override Collection<T> newCollection() { return new ArrayList<>(); } }; }
@Override public void bind(Moshi moshi, JsonAdapter.Factory factory) { super.bind(moshi, factory); delegate = Types.equals(parameterTypes[0], returnType) && qualifierAnnotations.equals(returnTypeAnnotations) ? moshi.nextAdapter(factory, returnType, returnTypeAnnotations) : moshi.adapter(returnType, returnTypeAnnotations); }
@Override public void bind(Moshi moshi, JsonAdapter.Factory factory) { super.bind(moshi, factory); delegate = Types.equals(parameterTypes[0], returnType) && qualifierAnnotations.equals(returnTypeAnnotations) ? moshi.nextAdapter(factory, parameterTypes[0], qualifierAnnotations) : moshi.adapter(parameterTypes[0], qualifierAnnotations); }
public void run() throws Exception { String json = "" + "{" + " \"username\": \"jesse\"," + " \"lucky number\": 32" + "}\n"; Moshi moshi = new Moshi.Builder().build(); JsonAdapter<Player> jsonAdapter = moshi.adapter(Player.class); Player player = jsonAdapter.fromJson(json); System.out.println(player); }
@Override public @Nullable JsonAdapter<?> create( Type type, Set<? extends Annotation> annotations, Moshi moshi) { Type elementType = Types.arrayComponentType(type); if (elementType == null) return null; if (!annotations.isEmpty()) return null; Class<?> elementClass = Types.getRawType(elementType); JsonAdapter<Object> elementAdapter = moshi.adapter(elementType); return new ArrayJsonAdapter(elementClass, elementAdapter).nullSafe(); } };
public static void main(String[] args) throws Exception { Moshi moshi = new Moshi.Builder() .add(FallbackEnumJsonAdapter.FACTORY) .build(); JsonAdapter<Example> adapter = moshi.adapter(Example.class); System.out.println(adapter.fromJson("{\"transportation\":\"CARS\"}")); }
@Override public void toJson(JsonWriter writer, Object value) throws IOException { Class<?> valueClass = value.getClass(); if (valueClass == Object.class) { // Don't recurse infinitely when the runtime type is also Object.class. writer.beginObject(); writer.endObject(); } else { moshi.adapter(toJsonType(valueClass), Util.NO_ANNOTATIONS).toJson(writer, value); } }
public void run() throws Exception { // We want to match any Stage that starts with 'in-progress' as Stage.IN_PROGRESS // and leave the rest of the enum values as to match as normal. Moshi moshi = new Moshi.Builder().add(new StageAdapter()).build(); JsonAdapter<Stage> jsonAdapter = moshi.adapter(Stage.class); System.out.println(jsonAdapter.fromJson("\"not-started\"")); System.out.println(jsonAdapter.fromJson("\"in-progress\"")); System.out.println(jsonAdapter.fromJson("\"in-progress-step1\"")); }
@Override public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) { JsonAdapter<?> adapter = moshi.adapter(type, jsonAnnotations(parameterAnnotations)); if (lenient) { adapter = adapter.lenient(); } if (failOnUnknown) { adapter = adapter.failOnUnknown(); } if (serializeNulls) { adapter = adapter.serializeNulls(); } return new MoshiRequestBodyConverter<>(adapter); }
@Override public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) { JsonAdapter<?> adapter = moshi.adapter(type, jsonAnnotations(annotations)); if (lenient) { adapter = adapter.lenient(); } if (failOnUnknown) { adapter = adapter.failOnUnknown(); } if (serializeNulls) { adapter = adapter.serializeNulls(); } return new MoshiResponseBodyConverter<>(adapter); }
public void run() throws Exception { String json = "\"TW9zaGksIE9saXZlLCBXaGl0ZSBDaGluPw\""; Moshi moshi = new Moshi.Builder() .add(ByteString.class, new Base64ByteStringAdapter()) .build(); JsonAdapter<ByteString> jsonAdapter = moshi.adapter(ByteString.class); ByteString byteString = jsonAdapter.fromJson(json); System.out.println(byteString); }
public void run() throws Exception { String json = "[\"DIAMONDS\", \"STARS\", \"HEARTS\"]"; Moshi moshi = new Moshi.Builder() .add(DefaultOnDataMismatchAdapter.newFactory(Suit.class, Suit.CLUBS)) .build(); JsonAdapter<List<Suit>> jsonAdapter = moshi.adapter( Types.newParameterizedType(List.class, Suit.class)); List<Suit> suits = jsonAdapter.fromJson(json); System.out.println(suits); }
public void run() throws Exception { Moshi moshi = new Moshi.Builder() .add(new MultipleFormatsCardAdapter()) .add(new CardStringAdapter()) .build(); JsonAdapter<Card> cardAdapter = moshi.adapter(Card.class); // Decode cards from one format or the other. System.out.println(cardAdapter.fromJson("\"5D\"")); System.out.println(cardAdapter.fromJson("{\"suit\": \"SPADES\", \"rank\": 5}")); // Cards are always encoded as strings. System.out.println(cardAdapter.toJson(new Card('5', Suit.CLUBS))); }
public void run() throws Exception { BlackjackHand blackjackHand = new BlackjackHand( new Card('6', SPADES), Arrays.asList(new Card('4', CLUBS), new Card('A', HEARTS))); Moshi moshi = new Moshi.Builder().build(); JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class); String json = jsonAdapter.toJson(blackjackHand); System.out.println(json); }