com.squareup.moshi.Moshi Java Examples

The following examples show how to use com.squareup.moshi.Moshi. 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: 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 #3
Source File: CustomAdapterFactory.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Override public @Nullable JsonAdapter<?> create(
    Type type, Set<? extends Annotation> annotations, Moshi moshi) {
  if (!annotations.isEmpty()) {
    return null; // Annotations? This factory doesn't apply.
  }

  if (!(type instanceof ParameterizedType)) {
    return null; // No type parameter? This factory doesn't apply.
  }

  ParameterizedType parameterizedType = (ParameterizedType) type;
  if (parameterizedType.getRawType() != SortedSet.class) {
    return null; // Not a sorted set? This factory doesn't apply.
  }

  Type elementType = parameterizedType.getActualTypeArguments()[0];
  JsonAdapter<Object> elementAdapter = moshi.adapter(elementType);

  return new SortedSetAdapter<>(elementAdapter).nullSafe();
}
 
Example #4
Source File: ReadJson.java    From moshi with Apache License 2.0 6 votes vote down vote up
public void run() throws Exception {
  String json = ""
      + "{\n"
      + "  \"hidden_card\": {\n"
      + "    \"rank\": \"6\",\n"
      + "    \"suit\": \"SPADES\"\n"
      + "  },\n"
      + "  \"visible_cards\": [\n"
      + "    {\n"
      + "      \"rank\": \"4\",\n"
      + "      \"suit\": \"CLUBS\"\n"
      + "    },\n"
      + "    {\n"
      + "      \"rank\": \"A\",\n"
      + "      \"suit\": \"HEARTS\"\n"
      + "    }\n"
      + "  ]\n"
      + "}\n";

  Moshi moshi = new Moshi.Builder().build();
  JsonAdapter<BlackjackHand> jsonAdapter = moshi.adapter(BlackjackHand.class);

  BlackjackHand blackjackHand = jsonAdapter.fromJson(json);
  System.out.println(blackjackHand);
}
 
Example #5
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 #6
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 #7
Source File: OAuthResponse.java    From okhttp-oauth2-client with Apache License 2.0 6 votes vote down vote up
protected OAuthResponse(Response response) throws IOException {
    this.response = response;
    if (response != null) {
        responseBody = response.body().string();

        if (Utils.isJsonResponse(response)) {
            Moshi moshi = new Moshi.Builder().build();
            if (response.isSuccessful()) {
                token = moshi.adapter(Token.class).fromJson(responseBody);
                jsonParsed = true;

                if (token.expires_in != null)
                    expiresAt = (token.expires_in * 1000) + System.currentTimeMillis();
            } else {
                try {
                    error = moshi.adapter(OAuthError.class).fromJson(responseBody);
                    jsonParsed = true;
                } catch (Exception e) {
                    error = new OAuthError(e);
                    jsonParsed = false;

                }
            }
        }
    }
}
 
Example #8
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 #9
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 6 votes vote down vote up
@Test public void nonUniqueSubtypes() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
          .withSubtype(Success.class, "success")
          .withSubtype(Success.class, "data")
          .withSubtype(Error.class, "error"))
      .build();

  JsonAdapter<Message> adapter = moshi.adapter(Message.class);

  assertThat(adapter.fromJson("{\"type\":\"success\",\"value\":\"Okay!\"}"))
      .isEqualTo(new Success("Okay!"));
  assertThat(adapter.fromJson("{\"type\":\"data\",\"value\":\"Data!\"}"))
      .isEqualTo(new Success("Data!"));
  assertThat(adapter.fromJson("{\"type\":\"error\",\"error_logs\":{\"order\":66}}"))
      .isEqualTo(new Error(Collections.<String, Object>singletonMap("order", 66d)));
  assertThat(adapter.toJson(new Success("Data!")))
      .isEqualTo("{\"type\":\"success\",\"value\":\"Data!\"}");
}
 
Example #10
Source File: CustomAdapterWithDelegate.java    From moshi with Apache License 2.0 5 votes vote down vote up
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\""));
}
 
Example #11
Source File: FallbackEnum.java    From moshi with Apache License 2.0 5 votes vote down vote up
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\"}"));
}
 
Example #12
Source File: BigDecimalAdapterTest.java    From rides-java-sdk with MIT License 5 votes vote down vote up
@Test
public void fromJson_shouldHandleAbsent_andNull_andNonNullValues() throws IOException {
    Moshi moshi = new Moshi.Builder().add(new BigDecimalAdapter()).build();

    JsonAdapter<BigDecimalModel> adapter = moshi.adapter(BigDecimalModel.class);
    BigDecimalModel model = adapter.fromJson("{\"nullDecimal\":null,\"presentDecimal\":1.23}");
    assertThat(model.absentDecimal).isNull();
    assertThat(model.nullDecimal).isNull();
    assertThat(model.presentDecimal).isEqualTo(new BigDecimal("1.23"));
}
 
Example #13
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 #14
Source File: TransientUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserializing_thenTransientFieldIgnored() throws IOException {
    Moshi moshi = new Moshi.Builder()
      .build();
    JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);

    String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}";
    Post post = jsonAdapter.fromJson(json);
    System.out.println(post);
}
 
Example #15
Source File: RecoverFromTypeMismatch.java    From moshi with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #16
Source File: ComplexAdapterUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializing_thenCorrectJsonProduced() {
    Moshi moshi = new Moshi.Builder()
      .add(new JsonDateTimeAdapter())
      .build();
    JsonAdapter<ZonedDateTime> jsonAdapter = moshi.adapter(ZonedDateTime.class);

    String json = jsonAdapter.toJson(ZonedDateTime.now());
    System.out.println(json);
}
 
Example #17
Source File: RenameUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenSerializing_thenRenamedFieldsGetConsumed() throws IOException {
    Moshi moshi = new Moshi.Builder()
      .build();
    JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);

    String json = "{\"authored_by\":\"Baeldung\",\"title\":\"My Post\"}";
    Post post = jsonAdapter.fromJson(json);
    System.out.println(post);
}
 
Example #18
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 #19
Source File: DefaultOnDataMismatchAdapter.java    From moshi with Apache License 2.0 5 votes vote down vote up
public static <T> Factory newFactory(final Class<T> type, final T defaultValue) {
  return new Factory() {
    @Override public @Nullable JsonAdapter<?> create(
        Type requestedType, Set<? extends Annotation> annotations, Moshi moshi) {
      if (type != requestedType) return null;
      JsonAdapter<T> delegate = moshi.nextAdapter(this, type, annotations);
      return new DefaultOnDataMismatchAdapter<>(delegate, defaultValue);
    }
  };
}
 
Example #20
Source File: ApiModule.java    From u2020 with Apache License 2.0 5 votes vote down vote up
@Provides @Singleton Retrofit provideRetrofit(HttpUrl baseUrl, @Named("Api") OkHttpClient client,
    Moshi moshi) {
  return new Retrofit.Builder() //
      .client(client) //
      .baseUrl(baseUrl) //
      .addConverterFactory(MoshiConverterFactory.create(moshi)) //
      .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) //
      .build();
}
 
Example #21
Source File: InfluxDBException.java    From influxdb-java with MIT License 5 votes vote down vote up
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);
  }
}
 
Example #22
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);
}
 
Example #23
Source File: PrimitiveUnitTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void whenDeserializing_thenCorrectJsonConsumed() throws IOException {
    Moshi moshi = new Moshi.Builder()
      .build();
    JsonAdapter<Post> jsonAdapter = moshi.adapter(Post.class);

    String json = "{\"author\":\"Baeldung\",\"text\":\"This is my post\",\"title\":\"My Post\"}";
    Post post = jsonAdapter.fromJson(json);
    System.out.println(post);
}
 
Example #24
Source File: DefaultOnDataMismatchAdapter.java    From moshi-lazy-adapters with Apache License 2.0 5 votes vote down vote up
/** Builds an adapter that fallbacks to a default value in case there's a mismatch. */
public static <T> JsonAdapter.Factory newFactory(final Type type, final T defaultValue) {
  return new Factory() {
    @Override public JsonAdapter<?> create(Type requestedType,
        Set<? extends Annotation> annotations, Moshi moshi) {
      if (Types.equals(type, requestedType)) {
        JsonAdapter<T> delegate = moshi.nextAdapter(this, type, annotations);
        return new DefaultOnDataMismatchAdapter<>(delegate, defaultValue);
      }

      return null;
    }
  };
}
 
Example #25
Source File: RidesServiceTest.java    From rides-java-sdk with MIT License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    Moshi moshi = new Moshi.Builder().add(new BigDecimalAdapter()).build();

    service = new Retrofit.Builder()
            .addConverterFactory(MoshiConverterFactory.create(moshi))
            .client(new OkHttpClient.Builder()
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .build())
            .baseUrl("http://localhost:" + wireMockRule.port())
            .build()
            .create(RidesService.class);
}
 
Example #26
Source File: TestUtil.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@SafeVarargs
public static Moshi moshi(boolean strict, Class<? extends Resource>... types) {
    ResourceAdapterFactory.Builder factoryBuilder = ResourceAdapterFactory.builder();
    factoryBuilder.add(types);
    if (!strict) {
        factoryBuilder.add(Default.class);
    }
    return new Moshi.Builder().add(factoryBuilder.build()).add(new ColorAdapter()).build();
}
 
Example #27
Source File: PolymorphicJsonAdapterFactoryTest.java    From moshi with Apache License 2.0 5 votes vote down vote up
@Test public void failOnUnknownMissingTypeLabel() throws IOException {
  Moshi moshi = new Moshi.Builder()
      .add(PolymorphicJsonAdapterFactory.of(Message.class, "type")
          .withSubtype(MessageWithType.class, "success"))
      .build();
  JsonAdapter<Message> adapter = moshi.adapter(Message.class).failOnUnknown();

  MessageWithType decoded = (MessageWithType) adapter.fromJson(
      "{\"value\":\"Okay!\",\"type\":\"success\"}");
  assertThat(decoded.value).isEqualTo("Okay!");
}
 
Example #28
Source File: DocumentTest.java    From moshi-jsonapi with MIT License 5 votes vote down vote up
@Test
public void deserialize_object_to_object_typed_document() throws Exception {
    Moshi moshi = TestUtil.moshi(Article.class);
    JsonAdapter<?> adapter = moshi.adapter(Types.newParameterizedType(ObjectDocument.class, Article.class));
    assertThat(adapter, instanceOf(ResourceAdapterFactory.DocumentAdapter.class));
    ObjectDocument<Article> objectDocument = ((ObjectDocument<Article>) adapter.fromJson(TestUtil.fromResource("/single.json")));
    assertThat(objectDocument, instanceOf(ObjectDocument.class));
    assertOnArticle1(objectDocument.<Article>asObjectDocument().get());
}
 
Example #29
Source File: OauthManager.java    From u2020 with Apache License 2.0 5 votes vote down vote up
@Inject public OauthManager(IntentFactory intentFactory, OkHttpClient client, Moshi moshi,
    @AccessToken Preference<String> accessToken) {
  this.intentFactory = intentFactory;
  this.client = client;
  this.moshi = moshi;
  this.accessToken = accessToken;
}
 
Example #30
Source File: VersionUtils.java    From SaliensAuto with GNU General Public License v3.0 5 votes vote down vote up
public static String getRemoteVersion(){
    String data = RequestUtils.githubApi("releases/latest");
    Moshi moshi = new Moshi.Builder().build();
    JsonAdapter<GithubRelease> jsonAdapter = moshi.adapter(GithubRelease.class);
    try {
        GithubRelease release = jsonAdapter.fromJson(data);
        return release.tag_name;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}