com.squareup.moshi.JsonDataException Java Examples

The following examples show how to use com.squareup.moshi.JsonDataException. 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: 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 #2
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void failOnNotFound() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  try {
    adapter.fromJson("{\n"
        + "  \"data\": {\n"
        + "    \"1\": {\n"
        + "      \"2\": null\n"
        + "    }\n"
        + "  }\n"
        + "}");
    fail();
  } catch (JsonDataException ex) {
    assertThat(ex).hasMessage(
        "Wrapped Json expected at path: [1, 2]. Found null at $.data.1.2");
  }
}
 
Example #3
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void notNullSafe() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  try {
    adapter.fromJson("{\n"
        + "  \"data\": null\n"
        + "}");
    fail();
  } catch (JsonDataException expected) {
  }

  Data2 data2 = new Data2();
  String toJson = adapter.toJson(data2);
  assertThat(toJson).isEqualTo("{}");

  toJson = adapter.serializeNulls().toJson(data2);
  assertThat(toJson).isEqualTo("{\"data\":{\"1\":{\"2\":null}}}");
}
 
Example #4
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void fromJsonOnIncorrectPath() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  try {
    adapter.fromJson("{\n"
        + "  \"data\": {\n"
        + "    \"2\": {\n"
        + "      \"1\": null\n"
        + "    }\n"
        + "  }\n"
        + "}");
    fail();
  } catch (JsonDataException e) {
    assertThat(e).hasMessage("Wrapped Json expected at path: [1, 2]. Actual: $.data");
  }
}
 
Example #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Test public void nonStringLabelValue() 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);

  try {
    adapter.fromJson("{\"type\":{},\"value\":\"Okay!\"}");
    fail();
  } catch (JsonDataException expected) {
    assertThat(expected).hasMessage("Expected a string but was BEGIN_OBJECT at path $.type");
  }
}
 
Example #12
Source File: CardAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@FromJson Card fromJson(String card) {
  if (card.length() != 2) throw new JsonDataException("Unknown card: " + card);

  char rank = card.charAt(0);
  switch (card.charAt(1)) {
    case 'C': return new Card(rank, Suit.CLUBS);
    case 'D': return new Card(rank, Suit.DIAMONDS);
    case 'H': return new Card(rank, Suit.HEARTS);
    case 'S': return new Card(rank, Suit.SPADES);
    default: throw new JsonDataException("unknown suit: " + card);
  }
}
 
Example #13
Source File: MultipleFormats.java    From moshi with Apache License 2.0 5 votes vote down vote up
@FromJson @CardString Card fromJson(String card) {
  if (card.length() != 2) throw new JsonDataException("Unknown card: " + card);

  char rank = card.charAt(0);
  switch (card.charAt(1)) {
    case 'C': return new Card(rank, Suit.CLUBS);
    case 'D': return new Card(rank, Suit.DIAMONDS);
    case 'H': return new Card(rank, Suit.HEARTS);
    case 'S': return new Card(rank, Suit.SPADES);
    default: throw new JsonDataException("unknown suit: " + card);
  }
}
 
Example #14
Source File: NonNullJsonAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override
public void toJson(JsonWriter writer, @Nullable T value) throws IOException {
  if (value == null) {
    throw new JsonDataException("Unexpected null at " + writer.getPath());
  } else {
    delegate.toJson(writer, value);
  }
}
 
Example #15
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 #16
Source File: FirstElementJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void fromJsonExpectsAnArray() throws Exception {
  JsonAdapter<Data> adapter = moshi.adapter(Data.class);

  try {
    adapter.fromJson("{\n"
        + "  \"obj\": \"this_will_throw\"\n"
        + "}");
    fail();
  } catch (JsonDataException e) {
    // Moshi's Collection adapter will throw
    assertThat(e).hasMessage("Expected BEGIN_ARRAY but was STRING at path $.obj");
  }
}
 
Example #17
Source File: LastElementJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void fromJsonExpectsAnArray() throws Exception {
  JsonAdapter<LastElementJsonAdapterTest.Data> adapter = moshi.adapter(Data.class);

  try {
    adapter.fromJson("{\n"
        + "  \"obj\": \"this_will_throw\"\n"
        + "}");
    fail();
  } catch (JsonDataException e) {
    // Moshi's Collection adapter will throw
    assertThat(e).hasMessage("Expected BEGIN_ARRAY but was STRING at path $.obj");
  }
}
 
Example #18
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void fromJsonDoesNotSwallowJsonDataExceptions() throws Exception {
  JsonAdapter<Data3> adapter = moshi.adapter(Data3.class);

  try {
    adapter.fromJson("{\n"
        + "  \"str\": {\n"
        + "    \"1\": false\n"
        + "  }\n"
        + "}");
    fail();
  } catch (JsonDataException e) {
    assertThat(e).hasMessage("Expected a string but was BOOLEAN at path $.str.1");
  }
}
 
Example #19
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void failOnNotFound2() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  try {
    adapter.fromJson("{\n"
        + "  \"data\": {\n"
        + "    \"1\": null\n"
        + "  }\n"
        + "}");
    fail();
  } catch (JsonDataException ex) {
    assertThat(ex).hasMessage(
        "Wrapped Json expected at path: [1, 2]. Found null at $.data.1");
  }
}
 
Example #20
Source File: FallbackEnumJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void ignoresUnannotatedEnums() throws Exception {
  JsonAdapter<Regular> adapter = moshi.adapter(Regular.class).lenient();
  assertThat(adapter.fromJson("\"ONE\"")).isEqualTo(Regular.ONE);

  try {
    adapter.fromJson("\"TWO\"");
    fail();
  } catch (JsonDataException expected) {
    assertThat(expected).hasMessage(
        "Expected one of [ONE] but was TWO at path $");
  }
}
 
Example #21
Source File: ElementAtJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void fromJsonExpectsAnArray() throws Exception {
  JsonAdapter<Data> adapter = moshi.adapter(Data.class);

  try {
    adapter.fromJson("{\n"
        + "  \"obj\": \"this_will_throw\"\n"
        + "}");
    fail();
  } catch (JsonDataException e) {
    // Moshi's Collection adapter will throw
    assertThat(e).hasMessage("Expected BEGIN_ARRAY but was STRING at path $.obj");
  }
}
 
Example #22
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 #23
Source File: LazyAdaptersRxJavaTest.java    From moshi-lazy-adapters with Apache License 2.0 4 votes vote down vote up
@Test public void reactiveTypeYieldsAppropriateError() throws Exception {
  //noinspection unchecked
  testConsumer
      .assertFailureAndMessage(JsonDataException.class,
          "Wrapped Json expected at path: [one, two, three]. Found null at $.one.two");
}
 
Example #24
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
@Test(expected = JsonDataException.class)
public void deserialize_no_default() throws Exception {
    TestUtil.moshi(true, Article.class)
            .adapter(Types.newParameterizedType(Document.class, Article.class))
            .fromJson(TestUtil.fromResource("/multiple_compound.json"));
}
 
Example #25
Source File: WrappedJsonAdapter.java    From moshi-lazy-adapters with Apache License 2.0 4 votes vote down vote up
/**
 * Recursively goes through the json and finds the given root. Returns the object wrapped by the
 * provided {@code path}.
 */
private static <T> T fromJson(JsonAdapter<T> adapter, JsonReader reader, String[] path,
    int index, boolean failOnNotFound) throws IOException {
  if (index == path.length) {
    //noinspection unchecked This puts full responsibility on the caller.
    return adapter.fromJson(reader);
  } else {
    reader.beginObject();
    Exception caughtException = null;
    try {
      String root = path[index];
      while (reader.hasNext()) {
        if (reader.nextName().equals(root)) {
          if (reader.peek() == JsonReader.Token.NULL) {
            // Consumer expects a value, not a null.
            if (failOnNotFound) {
              throw new JsonDataException(String.format(
                  "Wrapped Json expected at path: %s. Found null at %s",
                  Arrays.asList(path), reader.getPath()
              ));
            }

            return reader.nextNull();
          }
          return fromJson(adapter, reader, path, ++index, failOnNotFound);
        } else {
          reader.skipValue();
        }
      }
    } catch (Exception e) {
      caughtException = e;
    } finally {
      // If the try block throw an exception, rethrow it up the stack.
      if (caughtException instanceof IOException) {
        //noinspection ThrowFromFinallyBlock
        throw (IOException) caughtException;
      } else if (caughtException instanceof JsonDataException) {
        //noinspection ThrowFromFinallyBlock
        throw (JsonDataException) caughtException;
      } else if (caughtException != null) {
        //noinspection ThrowFromFinallyBlock
        throw new AssertionError(caughtException);
      }
      // If the json has an additional key, that was not red, we ignore it.
      while (reader.hasNext()) {
        reader.skipValue();
      }
      // End object, so that other adapters (if any) can proceed.
      reader.endObject();
    }
    throw new JsonDataException(String.format(
        "Wrapped Json expected at path: %s. Actual: %s",
        Arrays.asList(path), reader.getPath()));
  }
}
 
Example #26
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 4 votes vote down vote up
@Test(expected = JsonDataException.class)
public void deserialize_multiple_polymorphic_no_default() throws Exception {
    TestUtil.moshi(true, Article.class)
            .adapter(Types.newParameterizedType(Document.class, Resource.class))
            .fromJson(TestUtil.fromResource("/multiple_polymorphic.json"));
}