本文整理汇总了Java中com.squareup.moshi.Moshi类的典型用法代码示例。如果您正苦于以下问题:Java Moshi类的具体用法?Java Moshi怎么用?Java Moshi使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
Moshi类属于com.squareup.moshi包,在下文中一共展示了Moshi类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: performSerializeTests
import com.squareup.moshi.Moshi; //导入依赖的package包/类
private void performSerializeTests() {
mBarChart.clear();
mBarChart.setSections(new String[] {"Serialize 60 items", "Serialize 20 items", "Serialize 7 items", "Serialize 2 items"});
Gson gson = new Gson();
ObjectMapper objectMapper = new ObjectMapper();
Moshi moshi = new Moshi.Builder().build();
List<Serializer> serializers = new ArrayList<>();
for (Response response : mResponsesToSerialize) {
for (int iteration = 0; iteration < ITERATIONS; iteration++) {
serializers.add(new GsonSerializer(mSerializeListener, response, gson));
serializers.add(new JacksonDatabindSerializer(mSerializeListener, response, objectMapper));
serializers.add(new LoganSquareSerializer(mSerializeListener, response));
serializers.add(new MoshiSerializer(mSerializeListener, response, moshi));
}
}
for (Serializer serializer : serializers) {
serializer.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
示例2: SwapiModule
import com.squareup.moshi.Moshi; //导入依赖的package包/类
@Inject
public SwapiModule(OkHttpClient okHttpClient, Moshi moshi) {
final Retrofit swapiRetrofit = new Retrofit.Builder().baseUrl(Swapi.BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build();
bind(Swapi.class).toInstance(swapiRetrofit.create(Swapi.class));
final Retrofit searchRetrofit = new Retrofit.Builder().baseUrl(CustomSearch.BASE_URL)
.client(okHttpClient)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(MoshiConverterFactory.create(moshi))
.build();
bind(CustomSearch.class).toInstance(searchRetrofit.create(CustomSearch.class));
bind(SwapiListDataManager.class).singletonInScope();
}
示例3: performParseTests
import com.squareup.moshi.Moshi; //导入依赖的package包/类
private void performParseTests() {
mBarChart.clear();
mBarChart.setSections(new String[] {"Parse 60 items", "Parse 20 items", "Parse 7 items", "Parse 2 items"});
Gson gson = new Gson();
ObjectMapper objectMapper = new ObjectMapper();
Moshi moshi = new Moshi.Builder().build();
List<Parser> parsers = new ArrayList<>();
for (String jsonString : mJsonStringsToParse) {
for (int iteration = 0; iteration < ITERATIONS; iteration++) {
parsers.add(new GsonParser(mParseListener, jsonString, gson));
parsers.add(new JacksonDatabindParser(mParseListener, jsonString, objectMapper));
parsers.add(new MoshiParser(mParseListener, jsonString, moshi));
parsers.add(new LoganSquareParser(mParseListener, jsonString));
}
}
for (Parser parser : parsers) {
parser.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
}
示例4: IdService
import com.squareup.moshi.Moshi; //导入依赖的package包/类
public IdService(HDWallet wallet, String baseUrl) {
this.wallet = wallet;
//final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
this.client = new OkHttpClient.Builder();
addUserAgentHeader();
addSigningInterceptor();
addLogging();
final Moshi moshi = new Moshi.Builder().build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create(moshi))
//.addCallAdapterFactory(rxAdapter)
.client(client.build())
.build();
this.idInterface = retrofit.create(IdInterface.class);
}
示例5: BalanceService
import com.squareup.moshi.Moshi; //导入依赖的package包/类
public BalanceService(HDWallet wallet, String baseUrl) {
//final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory
// .createWithScheduler(Schedulers.io());
this.client = new OkHttpClient.Builder();
this.client.addInterceptor(new UserAgentInterceptor());
this.client.addInterceptor(new SigningInterceptor(wallet));
final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new LoggingInterceptor());
interceptor.setLevel(HttpLoggingInterceptor.Level.BASIC);
this.client.addInterceptor(interceptor);
final Moshi moshi = new Moshi.Builder()
.add(new BigIntegerAdapter())
.build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(client.build())
.build();
this.balanceInterface = retrofit.create(BalanceInterface.class);
}
示例6: testExecution
import com.squareup.moshi.Moshi; //导入依赖的package包/类
@Test
public void testExecution() throws Exception {
ApiPendingResult<Applet> pendingResult = new ApiPendingResult<>(Calls.<Applet>failure(new IOException()),
new Moshi.Builder().build().adapter(ErrorResponse.class));
final AtomicReference<ErrorResponse> errorResponseAtomicReference = new AtomicReference<>();
pendingResult.execute(new PendingResult.ResultCallback<Applet>() {
@Override
public void onSuccess(@NonNull Applet result) {
fail();
}
@Override
public void onFailure(@NonNull ErrorResponse errorResponse) {
errorResponseAtomicReference.set(errorResponse);
}
});
assertThat(errorResponseAtomicReference.get().code).isEqualTo("exception");
assertThat(errorResponseAtomicReference.get().message).isEqualTo("Unexpected error");
}
示例7: getCachedTranslationListObservable
import com.squareup.moshi.Moshi; //导入依赖的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();
}
});
}
示例8: getRemoteTranslationListObservable
import com.squareup.moshi.Moshi; //导入依赖的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);
}
});
}
示例9: writeTranslationList
import com.squareup.moshi.Moshi; //导入依赖的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);
}
}
示例10: OAuthResponse
import com.squareup.moshi.Moshi; //导入依赖的package包/类
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;
}
}
}
}
}
示例11: TestItemToJson
import com.squareup.moshi.Moshi; //导入依赖的package包/类
@Test
public void TestItemToJson() throws IOException {
Moshi moshi = new Moshi.Builder().add(Item.class, new ItemTypeAdapter()).build();
Item item = new Item.Builder()
.setId(1)
.setContentHash("oijoijo")
.setUnreadChanged(true)
.setUnread(false)
.build();
String itemJson = moshi.adapter(Item.class).toJson(item);
ReducedItem reducedItem = moshi.adapter(ReducedItem.class).fromJson(itemJson);
ReducedItem expectedReducedItem = new ReducedItem();
expectedReducedItem.id = 1;
expectedReducedItem.contentHash = "oijoijo";
expectedReducedItem.isUnread = false;
expectedReducedItem.isStarred = null;
assertEquals(expectedReducedItem, reducedItem);
}
示例12: getDocumentAdapter
import com.squareup.moshi.Moshi; //导入依赖的package包/类
public <T extends ResourceIdentifier> JsonAdapter<Document<T>> 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));
}
示例13: DirectoryService
import com.squareup.moshi.Moshi; //导入依赖的package包/类
private DirectoryService() {
final RxJavaCallAdapterFactory rxAdapter =
RxJavaCallAdapterFactory.createWithScheduler(Schedulers.io());
final File cachePath = new File(BaseApplication.get().getCacheDir(), "dirCache");
this.client = new OkHttpClient
.Builder()
.cache(new Cache(cachePath, 1024 * 1024 * 5))
.addNetworkInterceptor(new ReadFromCacheInterceptor())
.addInterceptor(new OfflineCacheInterceptor());
addUserAgentHeader();
addLogging();
final Moshi moshi = new Moshi.Builder()
.build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseApplication.get().getResources().getString(R.string.directory_url))
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(rxAdapter)
.client(client.build())
.build();
this.directoryInterface = retrofit.create(DirectoryInterface.class);
}
示例14: CurrencyService
import com.squareup.moshi.Moshi; //导入依赖的package包/类
private CurrencyService() {
final RxJavaCallAdapterFactory rxAdapter = RxJavaCallAdapterFactory
.createWithScheduler(Schedulers.io());
final File cachePath = new File(BaseApplication.get().getCacheDir(), "ratesCache");
this.client = new OkHttpClient
.Builder()
.cache(new Cache(cachePath, 1024 * 1024))
.addNetworkInterceptor(new ReadFromCacheInterceptor())
.addInterceptor(new OfflineCacheInterceptor());
addUserAgentHeader();
addLogging();
final Moshi moshi = new Moshi.Builder()
.add(new BigIntegerAdapter())
.add(new BigDecimalAdapter())
.build();
final Retrofit retrofit = new Retrofit.Builder()
.baseUrl(BaseApplication.get().getResources().getString(R.string.currency_url))
.addConverterFactory(MoshiConverterFactory.create(moshi))
.addCallAdapterFactory(rxAdapter)
.client(client.build())
.build();
this.currencyInterface = retrofit.create(CurrencyInterface.class);
}
示例15: PendingCommandSerializer
import com.squareup.moshi.Moshi; //导入依赖的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);
}