當前位置: 首頁>>代碼示例>>Java>>正文


Java JsonAdapter類代碼示例

本文整理匯總了Java中com.squareup.moshi.JsonAdapter的典型用法代碼示例。如果您正苦於以下問題:Java JsonAdapter類的具體用法?Java JsonAdapter怎麽用?Java JsonAdapter使用的例子?那麽, 這裏精選的類代碼示例或許可以為您提供幫助。


JsonAdapter類屬於com.squareup.moshi包,在下文中一共展示了JsonAdapter類的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Java代碼示例。

示例1: exchangeCode

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
/** See https://api.slack.com/methods/oauth.access. */
public OAuthSession exchangeCode(String code, HttpUrl redirectUrl) throws IOException {
  HttpUrl url = baseUrl.newBuilder("oauth.access")
      .addQueryParameter("client_id", clientId)
      .addQueryParameter("client_secret", clientSecret)
      .addQueryParameter("code", code)
      .addQueryParameter("redirect_uri", redirectUrl.toString())
      .build();
  Request request = new Request.Builder()
      .url(url)
      .build();
  Call call = httpClient.newCall(request);
  try (Response response = call.execute()) {
    JsonAdapter<OAuthSession> jsonAdapter = moshi.adapter(OAuthSession.class);
    return jsonAdapter.fromJson(response.body().source());
  }
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:18,代碼來源:SlackApi.java

示例2: enumValuesAreSerializedCorrectly

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@SuppressWarnings({"unchecked", "rawtypes"})
@Test
public void enumValuesAreSerializedCorrectly() throws ClassNotFoundException, NoSuchMethodException, SecurityException, InstantiationException, IllegalAccessException, IllegalArgumentException, InvocationTargetException {

    ClassLoader resultsClassLoader = schemaRule.generateAndCompile("/schema/enum/typeWithEnumProperty.json", "com.example",
            config("annotationStyle", "moshi1",
                    "propertyWordDelimiters", "_"));

    Class generatedType = resultsClassLoader.loadClass("com.example.TypeWithEnumProperty");
    Class enumType = resultsClassLoader.loadClass("com.example.TypeWithEnumProperty$EnumProperty");
    Object instance = generatedType.newInstance();

    Method setter = generatedType.getMethod("setEnumProperty", enumType);
    setter.invoke(instance, enumType.getEnumConstants()[3]);

    JsonAdapter jsonAdapter = moshi.adapter(generatedType);
    String json = jsonAdapter.toJson(instance);

    Map<String, String> jsonAsMap = new Gson().fromJson(json, Map.class);
    assertThat(jsonAsMap.get("enum_Property"), is("4 ! 1"));
}
 
開發者ID:weiwenqiang,項目名稱:GitHub,代碼行數:22,代碼來源:Moshi1IT.java

示例3: fromJson

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@FromJson
List<Applet> fromJson(JsonReader jsonReader, JsonAdapter<Applet> delegate) throws IOException {
    List<Applet> applets = new ArrayList<>();
    jsonReader.beginObject();
    while (jsonReader.hasNext()) {
        int index = jsonReader.selectName(OPTIONS);
        switch (index) {
            case -1:
                jsonReader.skipValue();
                break;
            case 0:
                jsonReader.beginArray();
                while (jsonReader.hasNext()) {
                    Applet applet = delegate.fromJson(jsonReader);
                    applets.add(applet);
                }
                jsonReader.endArray();
                break;
            default:
                throw new IllegalStateException("Unknown index: " + index);
        }
    }
    jsonReader.endObject();

    return applets;
}
 
開發者ID:IFTTT,項目名稱:IFTTTSDK-Android,代碼行數:27,代碼來源:AppletListJsonAdapter.java

示例4: getCachedTranslationListObservable

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
Observable<TranslationList> getCachedTranslationListObservable(final boolean forceDownload) {
  return Observable.defer(new Callable<ObservableSource<? extends TranslationList>>() {
    @Override
    public ObservableSource<TranslationList> call() throws Exception {
      boolean isCacheStale = System.currentTimeMillis() -
          quranSettings.getLastUpdatedTranslationDate() > Constants.MIN_TRANSLATION_REFRESH_TIME;
      if (forceDownload || isCacheStale) {
        return Observable.empty();
      }

      try {
        File cachedFile = getCachedFile();
        if (cachedFile.exists()) {
          Moshi moshi = new Moshi.Builder().build();
          JsonAdapter<TranslationList> jsonAdapter = moshi.adapter(TranslationList.class);
          return Observable.just(jsonAdapter.fromJson(Okio.buffer(Okio.source(cachedFile))));
        }
      } catch (Exception e) {
        Crashlytics.logException(e);
      }
      return Observable.empty();
    }
  });
}
 
開發者ID:Elias33,項目名稱:Quran,代碼行數:25,代碼來源:TranslationManagerPresenter.java

示例5: getRemoteTranslationListObservable

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
Observable<TranslationList> getRemoteTranslationListObservable() {
  return Observable.fromCallable(() -> {
    Request request = new Request.Builder()
        .url(host + WEB_SERVICE_ENDPOINT)
        .build();
    Response response = okHttpClient.newCall(request).execute();

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

    ResponseBody responseBody = response.body();
    TranslationList result = jsonAdapter.fromJson(responseBody.source());
    responseBody.close();
    return result;
  }).doOnNext(translationList -> {
    if (translationList.translations != null && !translationList.translations.isEmpty()) {
      writeTranslationList(translationList);
    }
  });
}
 
開發者ID:Elias33,項目名稱:Quran,代碼行數:21,代碼來源:TranslationManagerPresenter.java

示例6: writeTranslationList

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
void writeTranslationList(TranslationList list) {
  File cacheFile = getCachedFile();
  try {
    File directory = cacheFile.getParentFile();
    boolean directoryExists = directory.mkdirs() || directory.isDirectory();
    if (directoryExists) {
      if (cacheFile.exists()) {
        cacheFile.delete();
      }
      Moshi moshi = new Moshi.Builder().build();
      JsonAdapter<TranslationList> jsonAdapter = moshi.adapter(TranslationList.class);
      BufferedSink sink = Okio.buffer(Okio.sink(cacheFile));
      jsonAdapter.toJson(sink, list);
      sink.close();
      quranSettings.setLastUpdatedTranslationDate(System.currentTimeMillis());
    }
  } catch (Exception e) {
    cacheFile.delete();
    Crashlytics.logException(e);
  }
}
 
開發者ID:Elias33,項目名稱:Quran,代碼行數:22,代碼來源:TranslationManagerPresenter.java

示例7: readFrom

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@Override public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations,
    MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream)
    throws IOException, WebApplicationException {
  JsonAdapter<Object> adapter = moshi.adapter(genericType);
  BufferedSource source = Okio.buffer(Okio.source(entityStream));
  if (!source.request(1)) {
    throw new NoContentException("Stream is empty");
  }
  return adapter.fromJson(source);
  // Note: we do not close the InputStream per the interface documentation.
}
 
開發者ID:JakeWharton,項目名稱:jax-rs-moshi,代碼行數:12,代碼來源:MoshiMessageBodyReader.java

示例8: fromJson

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
/**
 * {@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) {
      }
    }
  }
}
 
開發者ID:VictorAlbertos,項目名稱:Jolyglot,代碼行數:21,代碼來源:MoshiSpeaker.java

示例9: personalListAccounts

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@Override
    public void personalListAccounts(Callback<PersonalListAccountsResponse> callback) throws IOException {

        Response response = httpClient.newCall(new Request.Builder().url(JSON_RPC_ENDPOINT)
                                                       .post(RequestBody.create(
                                                               JSON,
                                                               createListAccountRequest("personal_listAccounts")
                                                             )
                                                       )
                                                       .build()
        ).execute();

        JsonAdapter<PersonalListAccountsResponse> jsonAdapter = moshi.adapter(PersonalListAccountsResponse.class);
//        PersonalListAccountsResponse ethAccountsResponse = jsonAdapter.fromJson(response.body().source());
        String string = response.body().string();
        System.out.println("personal_listAccounts:  " + string);
        PersonalListAccountsResponse ethAccountsResponse = jsonAdapter.fromJson(string);

        callback.onResult(ethAccountsResponse);
    }
 
開發者ID:biafra23,項目名稱:EtherWallet,代碼行數:21,代碼來源:GethConnector.java

示例10: oneObject

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@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}}}}");
}
 
開發者ID:serj-lotutovici,項目名稱:moshi-lazy-adapters,代碼行數:21,代碼來源:WrappedJsonAdapterTest.java

示例11: failOnNotFound

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@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");
  }
}
 
開發者ID:serj-lotutovici,項目名稱:moshi-lazy-adapters,代碼行數:18,代碼來源:WrappedJsonAdapterTest.java

示例12: last

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
@Test public void last() throws Exception {
  JsonAdapter<LastElementJsonAdapterTest.Data>
      adapter = moshi.adapter(LastElementJsonAdapterTest.Data.class);

  LastElementJsonAdapterTest.Data fromJson = adapter.fromJson("{\n"
      + "  \"obj\": [\n"
      + "    \"one\",\n"
      + "    \"two\"\n"
      + "  ]\n"
      + "}");
  assertThat(fromJson.str).isEqualTo("two");

  String toJson = adapter.toJson(fromJson);
  // The excluded data is lost during parsing
  // Adapter under test assumes that the consumer doesn't need that data
  assertThat(toJson).isEqualTo("{\"obj\":[\"two\"]}");
}
 
開發者ID:serj-lotutovici,項目名稱:moshi-lazy-adapters,代碼行數:18,代碼來源:LastElementJsonAdapterTest.java

示例13: PendingCommandSerializer

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
private PendingCommandSerializer() {
    Moshi moshi = new Moshi.Builder().build();
    HashMap<String, JsonAdapter<? extends PendingCommand>> adapters = new HashMap<>();

    adapters.put(MessagingControllerCommands.COMMAND_MOVE_OR_COPY, moshi.adapter(PendingMoveOrCopy.class));
    adapters.put(MessagingControllerCommands.COMMAND_APPEND, moshi.adapter(PendingAppend.class));
    adapters.put(MessagingControllerCommands.COMMAND_EMPTY_TRASH, moshi.adapter(PendingEmptyTrash.class));
    adapters.put(MessagingControllerCommands.COMMAND_EXPUNGE, moshi.adapter(PendingExpunge.class));
    adapters.put(MessagingControllerCommands.COMMAND_MARK_ALL_AS_READ, moshi.adapter(PendingMarkAllAsRead.class));
    adapters.put(MessagingControllerCommands.COMMAND_SET_FLAG, moshi.adapter(PendingSetFlag.class));

    this.adapters = Collections.unmodifiableMap(adapters);
}
 
開發者ID:philipwhiuk,項目名稱:q-mail,代碼行數:14,代碼來源:PendingCommandSerializer.java

示例14: serialize

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
public <T extends PendingCommand> String serialize(T command) {
    // noinspection unchecked, we know the map has correctly matching adapters
    JsonAdapter<T> adapter = (JsonAdapter<T>) adapters.get(command.getCommandName());
    if (adapter == null) {
        throw new IllegalArgumentException("Unsupported pending command type!");
    }
    return adapter.toJson(command);
}
 
開發者ID:philipwhiuk,項目名稱:q-mail,代碼行數:9,代碼來源:PendingCommandSerializer.java

示例15: unserialize

import com.squareup.moshi.JsonAdapter; //導入依賴的package包/類
public PendingCommand unserialize(long databaseId, String commandName, String data) {
    JsonAdapter<? extends PendingCommand> adapter = adapters.get(commandName);
    if (adapter == null) {
        throw new IllegalArgumentException("Unsupported pending command type!");
    }
    try {
        PendingCommand command = adapter.fromJson(data);
        command.databaseId = databaseId;
        return command;
    } catch (IOException e) {
        throw new IOError(e);
    }
}
 
開發者ID:philipwhiuk,項目名稱:q-mail,代碼行數:14,代碼來源:PendingCommandSerializer.java


注:本文中的com.squareup.moshi.JsonAdapter類示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。