@Override public @Nullable T fromJson(JsonReader reader) throws IOException { return delegate.fromJson(reader); } @Override public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
public void run() throws Exception { Request request = new Request.Builder() .url("https://api.github.com/gists/c2a7c39532239ff261be") .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected code " + response); Gist gist = gistJsonAdapter.fromJson(response.body().source()); for (Map.Entry<String, GistFile> entry : gist.files.entrySet()) { System.out.println(entry.getKey()); System.out.println(entry.getValue().content); } } }
public static void main(String... args) throws Exception { OkHttpClient client = new OkHttpClient(); // Create request for remote resource. Request request = new Request.Builder() .url(ENDPOINT) .build(); // Execute the request and retrieve the response. try (Response response = client.newCall(request).execute()) { // Deserialize HTTP response to concrete type. ResponseBody body = response.body(); List<Contributor> contributors = CONTRIBUTORS_JSON_ADAPTER.fromJson(body.source()); // Sort list by the most contributions. Collections.sort(contributors, (c1, c2) -> c2.contributions - c1.contributions); // Output list of contributors. for (Contributor contributor : contributors) { System.out.println(contributor.login + ": " + contributor.contributions); } } }
/** 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()); } }
@Override public Object fromJson(Moshi moshi, JsonReader reader) throws IOException, InvocationTargetException { Object intermediate = delegate.fromJson(reader); return invoke(intermediate); } };
/** * Decodes a Java value object from {@code value}, which must be comprised of maps, lists, * strings, numbers, booleans and nulls. */ @CheckReturnValue public final @Nullable T fromJsonValue(@Nullable Object value) { JsonValueReader reader = new JsonValueReader(value); try { return fromJson(reader); } catch (IOException e) { throw new AssertionError(e); // No I/O reading from an object. } }
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\"")); }
/** 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()); } }
@Override public @Nullable T fromJson(JsonReader reader) throws IOException { if (reader.peek() == JsonReader.Token.NULL) { return reader.nextNull(); } else { return delegate.fromJson(reader); } } @Override public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
@Override public SortedSet<T> fromJson(JsonReader reader) throws IOException { TreeSet<T> result = new TreeSet<>(); reader.beginArray(); while (reader.hasNext()) { result.add(elementAdapter.fromJson(reader)); } reader.endArray(); return result; }
@Override public @Nullable T fromJson(JsonReader reader) throws IOException { if (reader.peek() == JsonReader.Token.NULL) { throw new JsonDataException("Unexpected null at " + reader.getPath()); } else { return delegate.fromJson(reader); } } @Override public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
@Override public @Nullable T fromJson(JsonReader reader) throws IOException { boolean lenient = reader.isLenient(); reader.setLenient(true); try { return delegate.fromJson(reader); } finally { reader.setLenient(lenient); } } @Override public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
@Override public @Nullable T fromJson(JsonReader reader) throws IOException { boolean skipForbidden = reader.failOnUnknown(); reader.setFailOnUnknown(true); try { return delegate.fromJson(reader); } finally { reader.setFailOnUnknown(skipForbidden); } } @Override public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
@CheckReturnValue public final @Nullable T fromJson(String string) throws IOException { JsonReader reader = JsonReader.of(new Buffer().writeUtf8(string)); T result = fromJson(reader); if (!isLenient() && reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; }
@Override public C fromJson(JsonReader reader) throws IOException { C result = newCollection(); reader.beginArray(); while (reader.hasNext()) { result.add(elementAdapter.fromJson(reader)); } reader.endArray(); return result; }
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 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\"}")); }
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); }
@Override public T convert(ResponseBody value) throws IOException { BufferedSource source = value.source(); try { // Moshi has no document-level API so the responsibility of BOM skipping falls to whatever // is delegating to it. Since it's a UTF-8-only library as well we only honor the UTF-8 BOM. if (source.rangeEquals(0, UTF8_BOM)) { source.skip(UTF8_BOM.size()); } JsonReader reader = JsonReader.of(source); T result = adapter.fromJson(reader); if (reader.peek() != JsonReader.Token.END_DOCUMENT) { throw new JsonDataException("JSON document was not fully consumed."); } return result; } finally { value.close(); } } }
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); }