本文整理匯總了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());
}
}
示例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"));
}
示例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;
}
示例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();
}
});
}
示例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);
}
});
}
示例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);
}
}
示例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.
}
示例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) {
}
}
}
}
示例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);
}
示例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}}}}");
}
示例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");
}
}
示例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\"]}");
}
示例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);
}
示例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);
}
示例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);
}
}