@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); }
@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; }
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))); }
/** 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()); } }
@Test public void asRegularEnumAdapter() throws Exception { JsonAdapter<Roshambo> adapter = moshi.adapter(Roshambo.class).lenient(); assertThat(adapter.fromJson("\"ROCK\"")).isEqualTo(Roshambo.ROCK); assertThat(adapter.toJson(Roshambo.PAPER)).isEqualTo("\"PAPER\""); // Check annotated value assertThat(adapter.fromJson("\"scr\"")).isEqualTo(Roshambo.SCISSORS); assertThat(adapter.toJson(Roshambo.SCISSORS)).isEqualTo("\"scr\""); }
public static InfluxDBException buildExceptionForErrorState(final String errorBody) { try { Moshi moshi = new Moshi.Builder().build(); JsonAdapter<ErrorMessage> adapter = moshi.adapter(ErrorMessage.class).lenient(); ErrorMessage errorMessage = adapter.fromJson(errorBody); return InfluxDBException.buildExceptionFromErrorMessage(errorMessage.error); } catch (Exception e) { return new InfluxDBException(errorBody); } }
@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 { 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); } } }
@Override public void toJson(JsonWriter writer, T value) throws IOException { delegate.toJson(writer, value); }
private <C extends Collection<String>> String toJson(Type collectionType, C collection) throws IOException { JsonAdapter<C> jsonAdapter = validCsAdapter(collectionType); Buffer buffer = new Buffer(); JsonWriter jsonWriter = JsonWriter.of(buffer); jsonWriter.setSerializeNulls(true); //noinspection ConstantConditions At this point the adapter should not be null. jsonAdapter.lenient().toJson(jsonWriter, collection); return buffer.readUtf8(); }
@SuppressWarnings("unchecked") private JsonAdapter<Phone> phoneAdapter() { return (JsonAdapter<Phone>) PhoneJsonAdapter.FACTORY.create( Phone.class, Collections.<Annotation>emptySet(), moshi).lenient(); } }
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\"")); }
public void run() throws Exception { // For some reason our JSON has date and time as separate fields. We will clean that up during // parsing: Moshi will first parse the JSON directly to an EventJson and from that the // EventJsonAdapter will create the actual Event. String json = "" + "{\n" + " \"title\": \"Blackjack tournament\",\n" + " \"begin_date\": \"20151010\",\n" + " \"begin_time\": \"17:04\"\n" + "}\n"; Moshi moshi = new Moshi.Builder().add(new EventJsonAdapter()).build(); JsonAdapter<Event> jsonAdapter = moshi.adapter(Event.class); Event event = jsonAdapter.fromJson(json); System.out.println(event); System.out.println(jsonAdapter.toJson(event)); }
@Override protected Node readValue(String source, String label, boolean lenient) { try { JsonAdapter<Object> adapter = moshi.adapter(Object.class); if (lenient) { adapter = adapter.lenient(); } return newNode(adapter.fromJson(source)); } catch (IOException e) { throw new IllegalArgumentException("Can not parse " + label + " value.", e); } }
public void run() throws Exception { Moshi moshi = new Moshi.Builder() .add(new SortedSetAdapterFactory()) .build(); JsonAdapter<SortedSet<String>> jsonAdapter = moshi.adapter( Types.newParameterizedType(SortedSet.class, String.class)); TreeSet<String> model = new TreeSet<>(); model.add("a"); model.add("b"); model.add("c"); String json = jsonAdapter.toJson(model); System.out.println(json); }
@Override public T fromJson(JsonReader reader) throws IOException { if (adapter == null) throw new IllegalStateException("JsonAdapter isn't ready"); return adapter.fromJson(reader); }