com.squareup.moshi.JsonAdapter Java Examples

The following examples show how to use com.squareup.moshi.JsonAdapter. 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: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Test public void unregisteredSubtype() {
  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.toJson(new EmptyMessage());
  } catch (IllegalArgumentException expected) {
    assertThat(expected).hasMessage("Expected one of [class"
        + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$Success, class"
        + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$Error] but found"
        + " EmptyMessage, a class"
        + " com.squareup.moshi.adapters.PolymorphicJsonAdapterFactoryTest$EmptyMessage. Register"
        + " this subtype.");
  }
}
 
Example #3
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 #4
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void oneObject() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  Data2 fromJson = adapter.fromJson("{\n"
      + "  \"data\": {\n"
      + "    \"1\": {\n"
      + "      \"2\": {\n"
      + "        \"str\": \"test\",\n"
      + "        \"val\": 42\n"
      + "      }\n"
      + "    }\n"
      + "  }\n"
      + "}");
  assertThat(fromJson).isNotNull();
  assertThat(fromJson.data.str).isEqualTo("test");
  assertThat(fromJson.data.val).isEqualTo(42);

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"data\":{\"1\":{\"2\":{\"str\":\"test\",\"val\":42}}}}");
}
 
Example #5
Source File: BoundParameterQueryTest.java    From influxdb-java with MIT License 6 votes vote down vote up
@Test
public void testGetParameterJsonWithUrlEncoded() throws IOException {
  BoundParameterQuery query = QueryBuilder.newQuery("SELECT * FROM abc WHERE integer > $i"
      + "AND double = $d AND bool = $bool AND string = $string AND other = $object")
      .forDatabase("foobar")
      .bind("i", 0)
      .bind("d", 1.0)
      .bind("bool", true)
      .bind("string", "test")
      .bind("object", new Object())
      .create();
  
  Moshi moshi = new Moshi.Builder().build();
  JsonAdapter<Point> adapter = moshi.adapter(Point.class);
  Point point = adapter.fromJson(decode(query.getParameterJsonWithUrlEncoded()));
  Assert.assertEquals(0, point.i);
  Assert.assertEquals(1.0, point.d, 0.0);
  Assert.assertEquals(true, point.bool);
  Assert.assertEquals("test", point.string);
  Assert.assertTrue(point.object.matches("java.lang.Object@[a-z0-9]+"));
}
 
Example #6
Source File: JsonApiConverterFactory.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
private JsonAdapter<?> getAdapterFromType(Type type) {
    Class<?> rawType = Types.getRawType(type);
    JsonAdapter<?> adapter;
    if (rawType.isArray() && ResourceIdentifier.class.isAssignableFrom(rawType.getComponentType())) {
        adapter = moshi.adapter(Types.newParameterizedType(Document.class, rawType.getComponentType()));
    } else if (List.class.isAssignableFrom(rawType) && type instanceof ParameterizedType) {
        Type typeParameter = ((ParameterizedType) type).getActualTypeArguments()[0];
        if (typeParameter instanceof Class<?> && ResourceIdentifier.class.isAssignableFrom((Class<?>) typeParameter)) {
            adapter = moshi.adapter(Types.newParameterizedType(Document.class, typeParameter));
        } else {
            return null;
        }
    } else if (ResourceIdentifier.class.isAssignableFrom(rawType)) {
        adapter = moshi.adapter(Types.newParameterizedType(Document.class, rawType));
    } else if (Document.class.isAssignableFrom(rawType)) {
        adapter = moshi.adapter(Types.newParameterizedType(Document.class, Resource.class));
    } else {
        return null;
    }
    return adapter;
}
 
Example #7
Source File: ReadJsonList.java    From moshi with Apache License 2.0 6 votes vote down vote up
public void run() throws Exception {
  String json = ""
      + "[\n"
      + "  {\n"
      + "    \"rank\": \"4\",\n"
      + "    \"suit\": \"CLUBS\"\n"
      + "  },\n"
      + "  {\n"
      + "    \"rank\": \"A\",\n"
      + "    \"suit\": \"HEARTS\"\n"
      + "  },\n"
      + "  {\n"
      + "    \"rank\": \"J\",\n"
      + "    \"suit\": \"SPADES\"\n"
      + "  }\n"
      + "]";

  Moshi moshi = new Moshi.Builder().build();

  Type listOfCardsType = Types.newParameterizedType(List.class, Card.class);
  JsonAdapter<List<Card>> jsonAdapter = moshi.adapter(listOfCardsType);

  List<Card> cards = jsonAdapter.fromJson(json);
  System.out.println(cards);
}
 
Example #8
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void fromJsonSkipsNonPathValues() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  Data2 fromJson = adapter.fromJson("{\n"
      + "  \"data\": {\n"
      + "    \"should_be_skipped\": null,\n"
      + "    \"1\": {\n"
      + "      \"2\": {\n"
      + "        \"str\": \"works\",\n"
      + "        \"val\": 11\n"
      + "      }\n"
      + "    }\n"
      + "\n"
      + "  }\n"
      + "}");

  assertThat(fromJson.data.str).isEqualTo("works");
  assertThat(fromJson.data.val).isEqualTo(11);
}
 
Example #9
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void fromJsonRemainingPathValues() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  Data2 fromJson = adapter.fromJson("{\n"
      + "  \"data\": {\n"
      + "    \"1\": {\n"
      + "      \"2\": {\n"
      + "        \"str\": \"works\",\n"
      + "        \"val\": 11\n"
      + "      }\n"
      + "    },\n"
      + "    \"should_be_skipped1\": null,\n"
      + "    \"should_be_skipped2\": null\n"
      + "  }\n"
      + "}");

  assertThat(fromJson.data.str).isEqualTo("works");
  assertThat(fromJson.data.val).isEqualTo(11);
}
 
Example #10
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 #11
Source File: FromJsonWithoutStrings.java    From moshi with Apache License 2.0 6 votes vote down vote up
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));
}
 
Example #12
Source File: WrappedJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void fromJsonDoesNotSwallowJsonEncodingExceptions() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  try {
    adapter.fromJson("{\n"
        + "  \"data\": {\n"
        + "    \"1\": {\n"
        + "      \"2\": {\n"
        + "        \"str\": \"valid\",\n"
        + "        \"val\": NaN\n"
        + "      }\n"
        + "    }\n"
        + "  }\n"
        + "}");
    fail();
  } catch (JsonEncodingException e) {
    assertThat(e).hasMessage(
        "Use JsonReader.setLenient(true) to accept malformed JSON at path $.data.1.2.val");
  }
}
 
Example #13
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 6 votes vote down vote up
public <T extends ResourceIdentifier> JsonAdapter<Document> getDocumentAdapter(Class<T> typeParameter,
                                                                               Class<? extends Resource>... knownTypes) {
    Moshi moshi;
    if (typeParameter == null) {
        return (JsonAdapter) TestUtil.moshi(knownTypes).adapter(Document.class);
    } else if (typeParameter.getAnnotation(JsonApi.class) != null) {
        Class<? extends Resource>[] types = new Class[knownTypes.length + 1];
        types[0] = (Class) typeParameter;
        for (int i = 0; i != knownTypes.length; i++) {
            types[i + 1] = knownTypes[i];
        }
        moshi = TestUtil.moshi(types);
    } else {
        moshi = TestUtil.moshi(knownTypes);
    }
    return moshi.adapter(Types.newParameterizedType(Document.class, typeParameter));
}
 
Example #14
Source File: SerializeOnlyNonEmptyJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 6 votes vote down vote up
@Test public void serializesOnlyNonEmptyCustomArray() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);

  Data1 fromJson = adapter.fromJson("{\n"
      + "\"customArray\": [{"
      + "\"data\":\"blub\""
      + "}]\n"
      + "}");
  assertThat(fromJson.customArray).isNotNull().hasSize(1);
  assertThat(fromJson.customArray[0].data).isEqualTo("blub");

  fromJson.customArray = new CustomType[0];
  assertThat(adapter.toJson(fromJson)).isEqualTo("{}");

  fromJson.customArray = new CustomType[] { new CustomType("blub") };
  assertThat(adapter.toJson(fromJson)).isEqualTo("{\"customArray\":[{\"data\":\"blub\"}]}");
}
 
Example #15
Source File: LastElementJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
private void assertNullReturn(String string) throws IOException {
  JsonAdapter<LastElementJsonAdapterTest.Data> adapter = moshi.adapter(Data.class);

  LastElementJsonAdapterTest.Data fromJson = adapter.fromJson(string);
  assertThat(fromJson.str).isNull();

  String toJson = adapter.toJson(fromJson);
  assertThat(toJson).isEqualTo("{\"obj\":[null]}");
}
 
Example #16
Source File: Unwrap.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Override public @Nullable JsonAdapter<?> create(
    Type type, Set<? extends Annotation> annotations, Moshi moshi) {
  Set<? extends Annotation> delegateAnnotations =
      Types.nextAnnotations(annotations, Enveloped.class);
  if (delegateAnnotations == null) {
    return null;
  }
  Type envelope =
      Types.newParameterizedTypeWithOwner(EnvelopeJsonAdapter.class, Envelope.class, type);
  JsonAdapter<Envelope<?>> delegate = moshi.nextAdapter(this, envelope, delegateAnnotations);
  return new EnvelopeJsonAdapter(delegate);
}
 
Example #17
Source File: TransientAutoValueTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void toStringReflectsInnerAdapter() throws Exception {
  JsonAdapter<String> adapter =
      moshi.adapter(String.class, Collections.singleton(new SerializeOnly() {
        @Override public Class<? extends Annotation> annotationType() {
          return Transient.class;
        }
      }));

  assertThat(adapter.toString()).isEqualTo("JsonAdapter(String).nullSafe().transient()");
}
 
Example #18
Source File: SerializeOnlyNonEmptyJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void serializesOnlyNonEmptyCollection() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);

  Data1 fromJson = adapter.fromJson("{\n"
      + "\"collection\": [\"blub\"]\n"
      + "}");
  assertThat(fromJson.collection).containsExactly("blub");

  fromJson.collection = new ArrayList<>(0);
  assertThat(adapter.toJson(fromJson)).isEqualTo("{}");

  fromJson.collection.add("blub");
  assertThat(adapter.toJson(fromJson)).isEqualTo("{\"collection\":[\"blub\"]}");
}
 
Example #19
Source File: UserPreferences.java    From android with Apache License 2.0 5 votes vote down vote up
public UserPreferences(SharedPreferences preferences, Moshi moshi) {
  RxSharedPreferences rxSharedPreferences = RxSharedPreferences.create(preferences);
  JsonAdapter<Nation> nationAdapter = moshi.adapter(Nation.class);
  JsonAdapter<Club> clubAdapter = moshi.adapter(Club.class);
  JsonAdapter<League> leagueAdapter = moshi.adapter(League.class);
  nationPreference = new JsonPreference<>(rxSharedPreferences, nationAdapter, KEY_USER_NATION);
  clubPreference = new JsonPreference<>(rxSharedPreferences, clubAdapter, KEY_USER_CLUB);
  leaguePreference = new JsonPreference<>(rxSharedPreferences, leagueAdapter, KEY_USER_LEAGUE);
  coachPreference = rxSharedPreferences.getString(KEY_COACH_NAME);
  coinsPreference = rxSharedPreferences.getLong(KEY_COINS);
  gameSpeedPreference = rxSharedPreferences.getInteger(KEY_GAME_SPEED, DEFAULT_GAME_SPEED);
}
 
Example #20
Source File: BigDecimalAdapterTest.java    From rides-java-sdk with MIT License 5 votes vote down vote up
@Test
public void toJson_shouldWork() {
    Moshi moshi = new Moshi.Builder().add(new BigDecimalAdapter()).build();
    JsonAdapter<BigDecimalModel> adapter = moshi.adapter(BigDecimalModel.class);
    BigDecimalModel bigDecimalModel = new BigDecimalModel();
    bigDecimalModel.presentDecimal = new BigDecimal("1.23");
    String json = adapter.toJson(bigDecimalModel);
    assertThat(json).isEqualTo("{\"presentDecimal\":1.23}");
}
 
Example #21
Source File: FallbackEnumJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void toStringReflectsInnerAdapter() throws Exception {
  JsonAdapter<Roshambo> adapter = moshi.adapter(Roshambo.class);

  assertThat(adapter.toString()).isEqualTo(
      "JsonAdapter(com.serjltt.moshi.adapters.FallbackEnumJsonAdapterTest$Roshambo)"
          + ".fallbackEnum(UNKNOWN).nullSafe()");
}
 
Example #22
Source File: ArrayUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserializingJsonArray_thenListProduced() throws IOException {
    Moshi moshi = new Moshi.Builder()
      .build();
    Type type = Types.newParameterizedType(List.class, String.class);
    JsonAdapter<List<String>> jsonAdapter = moshi.adapter(type);

    String json = "[\"One\",\"Two\",\"Three\"]";
    List<String> result = jsonAdapter.fromJson(json);
    System.out.println(result);
}
 
Example #23
Source File: ComplexAdapterUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserializing_thenCorrectJsonConsumed() throws IOException {
    Moshi moshi = new Moshi.Builder()
      .add(new JsonDateTimeAdapter())
      .build();
    JsonAdapter<ZonedDateTime> jsonAdapter = moshi.adapter(ZonedDateTime.class);

    String json = "{\"date\":\"2020-02-17\",\"time\":\"07:53:27.064\",\"timezone\":\"Europe/London\"}";
    ZonedDateTime now = jsonAdapter.fromJson(json);
    System.out.println(now);

}
 
Example #24
Source File: FallbackEnumJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@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\"");
}
 
Example #25
Source File: SerializeNullsJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void maintainsPreviousSerializationValue() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);
  Data1 data1 = new Data1();

  JsonWriter writer1 = JsonWriter.of(new Buffer());
  writer1.setSerializeNulls(true);
  adapter.toJson(writer1, data1);
  assertThat(writer1.getSerializeNulls()).isTrue();

  JsonWriter writer2 = JsonWriter.of(new Buffer());
  writer2.setSerializeNulls(false);
  adapter.toJson(writer2, data1);
  assertThat(writer2.getSerializeNulls()).isFalse();
}
 
Example #26
Source File: DeserializeOnlyJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void factoryMaintainsOtherAnnotations() throws Exception {
  JsonAdapter<Data2> adapter = moshi.adapter(Data2.class);

  Data2 fromJson = adapter.fromJson("{\"data\": \"test\"}");
  assertThat(fromJson.data).isEqualTo("testCustom");

  assertThat(adapter.toJson(fromJson)).isEqualTo("{}");
}
 
Example #27
Source File: SerializeOnlyJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void serializeOnly() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);

  Data1 fromJson = adapter.fromJson("{\"data\": \"test\"}");
  assertThat(fromJson.data).isNull();

  fromJson.data = "1234";
  assertThat(adapter.toJson(fromJson)).isEqualTo("{\"data\":\"1234\"}");
}
 
Example #28
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 #29
Source File: SerializeOnlyNonEmptyJsonAdapterTest.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
@Test public void serializesOnlyNonEmptyDoubleArray() throws Exception {
  JsonAdapter<Data1> adapter = moshi.adapter(Data1.class);

  Data1 fromJson = adapter.fromJson("{\n"
      + "\"doubleArray\": [1.0]\n"
      + "}");
  assertThat(fromJson.doubleArray).containsExactly(1.f);

  fromJson.doubleArray = new double[0];
  assertThat(adapter.toJson(fromJson)).isEqualTo("{}");

  fromJson.doubleArray = new double[] { 5f };
  assertThat(adapter.toJson(fromJson)).isEqualTo("{\"doubleArray\":[5.0]}");
}
 
Example #30
Source File: AlternativeAdapterUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializing_thenAlternativeAdapterUsed() {
    Moshi moshi = new Moshi.Builder()
      .add(new EpochMillisAdapter())
      .build();
    JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);

    String json = jsonAdapter.toJson(new Post("Introduction to Moshi Json", "Baeldung", Instant.now()));
    System.out.println(json);
}