com.squareup.moshi.JsonReader Java Examples

The following examples show how to use com.squareup.moshi.JsonReader. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MoshiSpeaker.java    From Jolyglot with Apache License 2.0 7 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public <T> T fromJson(File file, Class<T> classOfT) throws RuntimeException {
  BufferedSource bufferedSource = null;
  try {
    bufferedSource = Okio.buffer(Okio.source(file));
    JsonAdapter<T> jsonAdapter = moshi.adapter(classOfT);
    return jsonAdapter.fromJson(JsonReader.of(bufferedSource));
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if(bufferedSource != null){
      try {
        bufferedSource.close();
      } catch (IOException ignored) {
      }
    }
  }
}
 
Example #2
Source File: ResourceIdentifier.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
@Override
public ResourceIdentifier fromJson(JsonReader reader) throws IOException {
    ResourceIdentifier object = new ResourceIdentifier();
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            case "id":
                object.setId(nextNullableString(reader));
                break;
            case "type":
                object.setType(nextNullableString(reader));
                break;
            case "meta":
                object.setMeta(nextNullableObject(reader, jsonBufferJsonAdapter));
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();
    return object;
}
 
Example #3
Source File: MoshiConverterFactoryTest.java    From jus with Apache License 2.0 6 votes vote down vote up
@FromJson
public AnInterface read(JsonReader jsonReader) throws IOException {
    jsonReader.beginObject();

    String name = null;
    while (jsonReader.hasNext()) {
        switch (jsonReader.nextName()) {
            case "name":
                name = jsonReader.nextString();
                break;
        }
    }

    jsonReader.endObject();
    return new AnImplementation(name);
}
 
Example #4
Source File: MoshiSpeaker.java    From Jolyglot with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override public <T> T fromJson(File file, Type typeOfT) throws RuntimeException {
  BufferedSource bufferedSource = null;
  try {
    bufferedSource = Okio.buffer(Okio.source(file));
    JsonAdapter<T> jsonAdapter = moshi.adapter(typeOfT);
    return jsonAdapter.fromJson(JsonReader.of(bufferedSource));
  } catch (IOException e) {
    throw new RuntimeException(e);
  } finally {
    if(bufferedSource != null){
      try {
        bufferedSource.close();
      } catch (IOException ignored) {
      }
    }
  }
}
 
Example #5
Source File: HasOne.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
@Override
public HasOne<T> fromJson(JsonReader reader) throws IOException {
    HasOne<T> relationship = new HasOne<>();
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            case "data":
                relationship.set(nextNullableObject(reader, resourceIdentifierJsonAdapter));
                break;
            case "meta":
                relationship.setMeta(nextNullableObject(reader, jsonBufferJsonAdapter));
                break;
            case "links":
                relationship.setLinks(nextNullableObject(reader, jsonBufferJsonAdapter));
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();
    return relationship;
}
 
Example #6
Source File: DefaultOnDataMismatchAdapter.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Override public T fromJson(JsonReader reader) throws IOException {
  // Use a peeked reader to leave the reader in a known state even if there's an exception.
  JsonReader peeked = reader.peekJson();
  T result;
  try {
    // Attempt to decode to the target type with the peeked reader.
    result = delegate.fromJson(peeked);
  } catch (JsonDataException e) {
    result = defaultValue;
  } finally {
    peeked.close();
  }
  // Skip the value back on the reader, no matter the state of the peeked reader.
  reader.skipValue();
  return result;
}
 
Example #7
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Test public void nonObjectDoesNotConsume() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
          .withSubtype(Success.class, "success")
          .withSubtype(Error.class, "error"))
      .build();
  JsonAdapter<Message> adapter = moshi.adapter(Message.class);

  JsonReader reader = JsonReader.of(new Buffer().writeUtf8("\"Failure\""));
  try {
    adapter.fromJson(reader);
    fail();
  } catch (JsonDataException expected) {
    assertThat(expected).hasMessage("Expected BEGIN_OBJECT but was STRING at path $");
  }
  assertThat(reader.nextString()).isEqualTo("Failure");
  assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
 
Example #8
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Test public void unregisteredLabelValue() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
          .withSubtype(Success.class, "success")
          .withSubtype(Error.class, "error"))
      .build();
  JsonAdapter<Message> adapter = moshi.adapter(Message.class);

  JsonReader reader =
      JsonReader.of(new Buffer().writeUtf8("{\"type\":\"data\",\"value\":\"Okay!\"}"));
  try {
    adapter.fromJson(reader);
    fail();
  } catch (JsonDataException expected) {
    assertThat(expected).hasMessage("Expected one of [success, error] for key 'type' but found"
        + " 'data'. Register a subtype for this label.");
  }
  assertThat(reader.peek()).isEqualTo(JsonReader.Token.BEGIN_OBJECT);
}
 
Example #9
Source File: PolymorphicJsonAdapterFactory.java    From moshi with Apache License 2.0 6 votes vote down vote up
PolymorphicJsonAdapter(String labelKey,
    List<String> labels,
    List<Type> subtypes,
    List<JsonAdapter<Object>> jsonAdapters,
    @Nullable Object defaultValue,
    boolean defaultValueSet) {
  this.labelKey = labelKey;
  this.labels = labels;
  this.subtypes = subtypes;
  this.jsonAdapters = jsonAdapters;
  this.defaultValue = defaultValue;
  this.defaultValueSet = defaultValueSet;

  this.labelKeyOptions = JsonReader.Options.of(labelKey);
  this.labelOptions = JsonReader.Options.of(labels.toArray(new String[0]));
}
 
Example #10
Source File: EnumJsonAdapter.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Override public @Nullable T fromJson(JsonReader reader) throws IOException {
  int index = reader.selectString(options);
  if (index != -1) return constants[index];

  String path = reader.getPath();
  if (!useFallbackValue) {
    String name = reader.nextString();
    throw new JsonDataException("Expected one of "
        + Arrays.asList(nameStrings) + " but was " + name + " at path " + path);
  }
  if (reader.peek() != JsonReader.Token.STRING) {
    throw new JsonDataException(
        "Expected a string but was " + reader.peek() + " at path " + path);
  }
  reader.skipValue();
  return fallbackValue;
}
 
Example #11
Source File: Rfc3339DateJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public synchronized Date fromJson(JsonReader reader) throws IOException {
  if (reader.peek() == JsonReader.Token.NULL) {
    return reader.nextNull();
  }
  String string = reader.nextString();
  return Iso8601Utils.parse(string);
}
 
Example #12
Source File: MultipleFormats.java    From moshi with Apache License 2.0 5 votes vote down vote up
@FromJson Card fromJson(JsonReader reader, @CardString JsonAdapter<Card> stringAdapter,
    JsonAdapter<Card> defaultAdapter) throws IOException {
  if (reader.peek() == JsonReader.Token.STRING) {
    return stringAdapter.fromJson(reader);
  } else {
    return defaultAdapter.fromJson(reader);
  }
}
 
Example #13
Source File: CustomAdapterFactory.java    From moshi with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #14
Source File: CustomAdapterWithDelegate.java    From moshi with Apache License 2.0 5 votes vote down vote up
@FromJson
@Nullable
Stage fromJson(JsonReader jsonReader, JsonAdapter<Stage> delegate) throws IOException {
  String value = jsonReader.nextString();

  Stage stage;
  if (value.startsWith("in-progress")) {
    stage = Stage.IN_PROGRESS;
  } else {
    stage = delegate.fromJsonValue(value);
  }
  return stage;
}
 
Example #15
Source File: PolymorphicJsonAdapterFactory.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public Object fromJson(JsonReader reader) throws IOException {
  JsonReader peeked = reader.peekJson();
  peeked.setFailOnUnknown(false);
  int labelIndex;
  try {
    labelIndex = labelIndex(peeked);
  } finally {
    peeked.close();
  }
  if (labelIndex == -1) {
    reader.skipValue();
    return defaultValue;
  }
  return jsonAdapters.get(labelIndex).fromJson(reader);
}
 
Example #16
Source File: ModelListAdapterTest.java    From android with Apache License 2.0 5 votes vote down vote up
@Test public void testModelListAdapter() throws IOException {
  Buffer buffer = new Buffer();
  JsonWriter jsonWriter = JsonWriter.of(buffer);
  JsonAdapter<List<Nation>> adapter =
      moshi.adapter(Types.newParameterizedType(List.class, Nation.class));
  Nation nation = Nation.create(1, 1, "foo", "bar", "baz");
  List<Nation> nations = Collections.singletonList(nation);
  adapter.toJson(jsonWriter, nations);
  String json = buffer.readUtf8();
  buffer = new Buffer().writeUtf8(json);
  JsonReader jsonReader = JsonReader.of(buffer);
  assertThat(adapter.fromJson(jsonReader)).isEqualTo(nations);
}
 
Example #17
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Test public void nullSafe() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
          .withSubtype(Success.class, "success")
          .withSubtype(Error.class, "error"))
      .build();
  JsonAdapter<Message> adapter = moshi.adapter(Message.class);

  JsonReader reader = JsonReader.of(new Buffer().writeUtf8("null"));
  assertThat(adapter.fromJson(reader)).isNull();
  assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
 
Example #18
Source File: EnumJsonAdapterTest.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Test public void withoutFallbackValue() throws Exception {
  EnumJsonAdapter<Roshambo> adapter = EnumJsonAdapter.create(Roshambo.class);
  JsonReader reader = JsonReader.of(new Buffer().writeUtf8("\"SPOCK\""));
  try {
    adapter.fromJson(reader);
    fail();
  } catch (JsonDataException expected) {
    assertThat(expected).hasMessage(
        "Expected one of [ROCK, PAPER, scr] but was SPOCK at path $");
  }
  assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
 
Example #19
Source File: EnumJsonAdapterTest.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Test public void withFallbackValue() throws Exception {
  EnumJsonAdapter<Roshambo> adapter = EnumJsonAdapter.create(Roshambo.class)
      .withUnknownFallback(Roshambo.ROCK);
  JsonReader reader = JsonReader.of(new Buffer().writeUtf8("\"SPOCK\""));
  assertThat(adapter.fromJson(reader)).isEqualTo(Roshambo.ROCK);
  assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
 
Example #20
Source File: EnumJsonAdapterTest.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Test public void withNullFallbackValue() throws Exception {
  EnumJsonAdapter<Roshambo> adapter = EnumJsonAdapter.create(Roshambo.class)
      .withUnknownFallback(null);
  JsonReader reader = JsonReader.of(new Buffer().writeUtf8("\"SPOCK\""));
  assertThat(adapter.fromJson(reader)).isNull();
  assertThat(reader.peek()).isEqualTo(JsonReader.Token.END_DOCUMENT);
}
 
Example #21
Source File: NonNullJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Nullable
@Override
public 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);
  }
}
 
Example #22
Source File: NullSafeJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public @Nullable T fromJson(JsonReader reader) throws IOException {
  if (reader.peek() == JsonReader.Token.NULL) {
    return reader.nextNull();
  } else {
    return delegate.fromJson(reader);
  }
}
 
Example #23
Source File: Util.java    From moshi with Apache License 2.0 5 votes vote down vote up
public static JsonDataException missingProperty(
    String propertyName,
    String jsonName,
    JsonReader reader
) {
  String path = reader.getPath();
  String message;
  if (jsonName.equals(propertyName)) {
    message = String.format("Required value '%s' missing at %s", propertyName, path);
  } else {
    message = String.format("Required value '%s' (JSON name '%s') missing at %s",
        propertyName, jsonName, path);
  }
  return new JsonDataException(message);
}
 
Example #24
Source File: Util.java    From moshi with Apache License 2.0 5 votes vote down vote up
public static JsonDataException unexpectedNull(
    String propertyName,
    String jsonName,
    JsonReader reader
) {
  String path = reader.getPath();
  String message;
  if (jsonName.equals(propertyName)) {
    message = String.format("Non-null value '%s' was null at %s", propertyName, path);
  } else {
    message = String.format("Non-null value '%s' (JSON name '%s') was null at %s",
        propertyName, jsonName, path);
  }
  return new JsonDataException(message);
}
 
Example #25
Source File: HasMany.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Override
public HasMany<T> fromJson(JsonReader reader) throws IOException {
    HasMany<T> relationship = new HasMany<>();
    reader.beginObject();
    while (reader.hasNext()) {
        switch (reader.nextName()) {
            case "data":
                if (reader.peek() == JsonReader.Token.NULL) {
                    relationship.hasData = false;
                    reader.nextNull();
                } else {
                    reader.beginArray();
                    while (reader.hasNext()) {
                        relationship.add(resourceIdentifierJsonAdapter.fromJson(reader));
                    }
                    reader.endArray();
                }
                break;
            case "meta":
                relationship.setMeta(nextNullableObject(reader, jsonBufferJsonAdapter));
                break;
            case "links":
                relationship.setLinks(nextNullableObject(reader, jsonBufferJsonAdapter));
                break;
            default:
                reader.skipValue();
                break;
        }
    }
    reader.endObject();
    return relationship;
}
 
Example #26
Source File: TransientJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Override public T fromJson(JsonReader reader) throws IOException {
  if (deserialize) {
    return delegate.fromJson(reader);
  } else {
    reader.skipValue();
    return null;
  }
}
 
Example #27
Source File: DefaultOnDataMismatchAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Override public T fromJson(JsonReader reader) throws IOException {
  Object jsonValue = reader.readJsonValue();

  try {
    return delegate.fromJsonValue(jsonValue);
  } catch (JsonDataException ignore) {
    return defaultValue;
  }
}
 
Example #28
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
public static String nextNullableString(JsonReader reader) throws IOException {
    if (reader.peek() == JsonReader.Token.NULL) {
        reader.skipValue();
        return null;
    } else {
        return reader.nextString();
    }
}
 
Example #29
Source File: MoshiHelper.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
public static <T> T nextNullableObject(JsonReader reader, JsonAdapter<T> adapter) throws IOException {
    if (reader.peek() == JsonReader.Token.NULL) {
        reader.skipValue();
        return null;
    } else {
        return adapter.fromJson(reader);
    }
}
 
Example #30
Source File: FallbackOnNullJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Override public T fromJson(JsonReader reader) throws IOException {
  if (reader.peek() == JsonReader.Token.NULL) {
    reader.nextNull(); // We need to consume the value.
    return fallback;
  }
  return delegate.fromJson(reader);
}