Java 类com.google.gson.Gson 实例源码
项目:weixin_api
文件:MpUserApi.java
/**
* 创建用户标签
*
* @param name
* @return
* @throws ClientProtocolException
* @throws URISyntaxException
* @throws IOException
* @throws AccessTokenFailException
*/
public TagsCreateResp apiTagsCreate(String name)
throws ClientProtocolException, URISyntaxException, IOException, AccessTokenFailException {
MpAccessToken token = mpApi.apiToken();
String path = String.format("/tags/create?access_token=%s", token.getAccessToken());
TreeMap<String, Object> tag = new TreeMap<String, Object>();
tag.put("name", name);
TreeMap<String, Object> reqMap = new TreeMap<String, Object>();
reqMap.put("tag", tag);
String respText = HttpUtil.post(mpApi.config.getApiHttps(), path, reqMap);
TagsCreateResp resp = new Gson().fromJson(respText, TagsCreateResp.class);
if (mpApi.log.isInfoEnabled()) {
mpApi.log.info(String.format("apiTagsCreate %s", new Gson().toJson(resp)));
}
return resp;
}
项目:GitHub
文件:MainActivity.java
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);
}
}
项目:GCSApp
文件:IntroducePresenter.java
public void getData() {
LoginData loginData = (LoginData) aCache.getAsObject(ACacheKey.CURRENT_ACCOUNT);
addSubscription(apiStores.GetCsgData(loginData.getToken(), 1, 3), new ApiCallback<BaseModel<JsonArray>>(delegate.getActivity()) {
@Override
public void onSuccess(BaseModel<JsonArray> model) {
// ToastUtil.showToast("请求成功" + model.getData().toString(), delegate.getActivity());
// delegate.setData(model.getData());
F.e(model.getData().toString());
GsonBuilder gsonBuilder = new GsonBuilder();
Gson gson = gsonBuilder.create();
ArrayList<CSGDynamic> datas = gson.fromJson(model.getData(), new TypeToken<ArrayList<CSGDynamic>>() {
}.getType());
delegate.setData(datas);
}
@Override
public void onFailure(String msg) {
ToastUtil.showToast(msg, delegate.getActivity());
}
@Override
public void onFinish() {
}
});
}
项目:microbit
文件:BluetoothUtils.java
public static BluetoothDevice getPairedDeviceMicroBit(Context context) {
SharedPreferences pairedDevicePref = context.getApplicationContext().getSharedPreferences(PREFERENCES_KEY,
Context.MODE_MULTI_PROCESS);
if(pairedDevicePref.contains(PREFERENCES_PAIREDDEV_KEY)) {
String pairedDeviceString = pairedDevicePref.getString(PREFERENCES_PAIREDDEV_KEY, null);
Gson gson = new Gson();
sConnectedDevice = gson.fromJson(pairedDeviceString, ConnectedDevice.class);
//Check if the microbit is still paired with our mobile
BluetoothAdapter mBluetoothAdapter = ((BluetoothManager) MBApp.getApp().getSystemService(Context
.BLUETOOTH_SERVICE)).getAdapter();
if(mBluetoothAdapter.isEnabled()) {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
for(BluetoothDevice bt : pairedDevices) {
if(bt.getAddress().equals(sConnectedDevice.mAddress)) {
return bt;
}
}
}
}
return null;
}
项目:BIMplatform
文件:JsonGeometryQueryAction.java
public void sendGeometryParam(Double zoom, Vector3f middle) {
if (webSocketSession == null || !webSocketSession.isOpen()) {
return;
}
ResultUtil result = new ResultUtil();
result.setKeyValue("zoom", zoom);
result.setKeyValue("middle", middle);
result.setSuccess(true);
Gson gson = new Gson();
String jsonStr = gson.toJson(result.getResult());
TextMessage message = new TextMessage(jsonStr);
try {
webSocketSession.sendMessage(message);
} catch (Exception e) {
try {
webSocketSession.close();
} catch (IOException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}
}
项目:Jerkoff
文件:GraphAdapterBuilderTest.java
@Test
public void testDeserializationWithMultipleTypes() {
GsonBuilder gsonBuilder = new GsonBuilder();
new GraphAdapterBuilder().addType(Company.class).addType(Employee.class)
.registerOn(gsonBuilder);
Gson gson = gsonBuilder.create();
String json = "{'0x1':{'name':'Google','employees':['0x2','0x3']},"
+ "'0x2':{'name':'Jesse','company':'0x1'},"
+ "'0x3':{'name':'Joel','company':'0x1'}}";
Company company = gson.fromJson(json, Company.class);
assertEquals("Google", company.name);
Employee jesse = company.employees.get(0);
assertEquals("Jesse", jesse.name);
assertEquals(company, jesse.company);
Employee joel = company.employees.get(1);
assertEquals("Joel", joel.name);
assertEquals(company, joel.company);
}
项目:DYB
文件:DMController.java
@PostMapping("/add")
@ResponseBody
public String danMuAdd() {
Map<String, String> user = new HashMap<>();
DanMu danMu = new DanMu();
String userName = DMClient.getName();
String userText = DMClient.getText();
danMu.setName(userName);
danMu.setText(userText);
if(userName == null)
return null;
if (userName.equals(preName)) {
return null;
}
preName = userName;
dmRepository.save(danMu);
Gson gson = new Gson();
user.put("name", userName);
user.put("text", userText);
String gsonStr = gson.toJson(user);
return gsonStr;
}
项目:Forge
文件:FileManager.java
/**
* Replaces an existing Forge account in the storage
*
* @param context calling context
* @param account the Forge account to replace the original with
* @return the account added to the storage, if it's a failure returns null
*/
public static ForgeAccount replace(Context context, ForgeAccount account) {
// Initialise GSON
Gson gson = new Gson();
// Get the already saved Forge accounts
HashMap<UUID, ForgeAccount> accounts = FileManager.load(context);
// Replace the account with the matching UUID with the new account details
accounts.put(account.getId(), account);
// Convert the list of Forge Accounts to a JSON string
String jsonString = gson.toJson(new ArrayList<>(accounts.values()));
// Internal save
FileOutputStream outputStream;
try {
// Save the JSON to the file
outputStream = context.openFileOutput(context.getString(R.string.filename_forge_accounts), Context.MODE_PRIVATE);
outputStream.write(jsonString.getBytes());
outputStream.close();
return account;
} catch (Exception e) {
// If there is an error, log it
Log.e(Forge.ERROR_LOG, e.getMessage());
return null;
}
}
项目:Slide-RSS
文件:HttpUtil.java
/**
* Gets a JsonObject by calling apiUrl and parsing the JSON response String. This method accepts
* a Map that can contain custom headers to include in the request.
*
* @param client The OkHTTP client to use to make the request
* @param gson The GSON instance to use to parse the response String
* @param apiUrl The URL to call to get the response from
* @param headersMap The headers to include in the request. Can be null to not add any headers
* @return A JsonObject representation of the API response, null when there was an error or
* Exception thrown by the HTTP call
*/
public static JsonObject getJsonObject(final OkHttpClient client, final Gson gson,
final String apiUrl, @Nullable final Map<String, String> headersMap) {
if (client == null || gson == null || TextUtils.isEmpty(apiUrl)) return null;
Request.Builder builder = new Request.Builder().url(apiUrl);
if (headersMap != null && headersMap.size() > 0) {
// Add headers to the request if headers are available
for (Map.Entry<String, String> entry : headersMap.entrySet()) {
builder.addHeader(entry.getKey(), entry.getValue());
}
}
Request request = builder.build();
try {
Response response = client.newCall(request).execute();
if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
ResponseBody responseBody = response.body();
String json = responseBody.string();
responseBody.close();
return gson.fromJson(json, JsonObject.class);
} catch (JsonSyntaxException | IOException e) {
LogUtil.e(e, "Error " + apiUrl);
}
return null;
}
项目:OfflineSampleApp
文件:RemoteCommentService.java
public RemoteCommentService() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient httpClient = new OkHttpClient.Builder()
.addInterceptor(loggingInterceptor)
.build();
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.create();
retrofit = new Retrofit.Builder()
.client(httpClient)
.baseUrl(BuildConfig.API_BASE_URL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
}
项目:Trackr
文件:MainMenuActivity.java
public void loadProfileInformation() {
NavigationView navigationView = (NavigationView) findViewById(R.id.navigationView);
View header = navigationView.getHeaderView(0);
textView_profile_id = (TextView) header.findViewById(R.id.textViewProfileId);
textView_profile_name = (TextView) header.findViewById(R.id.textViewProfileName);
textView_profile_phone = (TextView) header.findViewById(R.id.textViewProfilePhone);
Gson gson = new Gson();
String json = sharedPreferencesProfileInformation.getString("currentUser", "");
currentUser = gson.fromJson(json, User.class);
textView_profile_id.setText(String.valueOf(currentUser.getId()));
textView_profile_name.setText(currentUser.getFname() + " " + currentUser.getLname());
textView_profile_phone.setText(currentUser.getPhone());
}
项目:TextReader
文件:RxUtil.java
public static <T> Observable rxCreateDiskObservable(final String key, final Class<T> clazz) {
return Observable.create(new Observable.OnSubscribe<String>() {
@Override
public void call(Subscriber<? super String> subscriber) {
LogUtils.d("get data from disk: key==" + key);
String json = ACache.get(ReaderApplication.getsInstance()).getAsString(key);
LogUtils.d("get data from disk finish , json==" + json);
if (!TextUtils.isEmpty(json)) {
subscriber.onNext(json);
}
subscriber.onCompleted();
}
})
.map(new Func1<String, T>() {
@Override
public T call(String s) {
return new Gson().fromJson(s, clazz);
}
})
.subscribeOn(Schedulers.io());
}
项目:nifi-config
文件:ExtractProcessorServiceTest.java
@Test
public void extractEmptyBranchTest() throws ApiException, IOException, URISyntaxException {
List<String> branch = Arrays.asList("root", "elt1");
File temp = File.createTempFile("tempfile", ".tmp");
ProcessGroupFlowEntity response = TestUtils.createProcessGroupFlowEntity("idComponent", "nameComponent");
when(processGroupServiceMock.changeDirectory(branch)).thenReturn(Optional.of(response));
when(flowapiMock.getControllerServicesFromGroup("idComponent")).thenReturn(new ControllerServicesEntity());
extractService.extractByBranch(branch, temp.getAbsolutePath());
//evaluate response
Gson gson = new Gson();
try (Reader reader = new InputStreamReader(new FileInputStream(temp), "UTF-8")) {
GroupProcessorsEntity result = gson.fromJson(reader, GroupProcessorsEntity.class);
assertTrue(result.getProcessors().isEmpty());
assertTrue(result.getGroupProcessorsEntity().isEmpty());
assertEquals("nameComponent", result.getName());
}
}
项目:DaiGo
文件:Order.java
@Override
public void convertJSON(String json) {
Gson gson = new Gson();
OrderDAO order = gson.fromJson(json, OrderDAO.class);
this.orderId = order.getOrderId();
this.orderSender = order.getOrderSender();
this.orderReceiver = order.getOrderReceiver();
this.acceptTime = order.getAcceptTime();
this.title = order.getTitle();
this.publicDetails = order.getPublicDetails();
this.privateDetails = order.getPrivateDetails();
this.requestTime = order.getRequestTime();
this.orderState = order.getOrderState();
this.price = order.getPrice();
this.contact = order.getContact();
this.completeTime = order.getCompleteTime();
}
项目:subreddify-android
文件:PollerModule.java
@Provides
public RedditResource provideRedditResource() {
Type redditPostListType = new TypeToken<List<RedditPost>>() {}.getType();
Gson gson = new GsonBuilder()
.registerTypeAdapter(redditPostListType, new RedditPostsDeserializer())
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://www.reddit.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
return retrofit.create(RedditResource.class);
}
项目:Roblox4j
文件:BasicRobloxian.java
@Override
public Badge[] getBadges() throws Exception {
List<Badge> badges = new ArrayList<>();
String url = "https://www.roblox" +
".com/users/inventory/list-json?assetTypeId=21&cursor=&itemsPerPage=100" +
"&pageNumber=1&sortOrder=Desc&userId=" + this.getUserId();
BadgesResponse response = new Gson().fromJson(Jsoup.connect(url).ignoreContentType(true)
.get().body().text(), BadgesResponse.class);
for (BadgesResponse.BadgesData.PlayerBadgeData item : response.Data.Items) {
badges.add(new Badge(item.Item.AssetId, item.Item.Name));
}
// next page
if (response.Data.nextPageCursor != null) {
badges.addAll(recursiveBadgeRetrieve(response));
}
return badges.toArray(new Badge[badges.size()]);
}
项目:Quicksend
文件:TemplateStorage.java
public List<Template> getAll(Context context) {
SharedPreferences settings;
List<Template> templates;
settings = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
if (settings.contains(DATA)) {
String json = settings.getString(DATA, null);
Gson gson = new Gson();
Template[] templates1 = gson.fromJson(json, Template[].class);
templates = Arrays.asList(templates1);
} else {
return null;
}
return templates;
}
项目:starcraft-2-build-player
文件:JsonBuildService.java
/**
* Parses a JSON input stream, returning a list of Build objects.
*/
public static ArrayList<Build> readBuildsFromJsonInputStream(InputStream input) throws IOException, JsonSyntaxException {
Gson gson = new GsonBuilder()
.setDateFormat(DbAdapter.DATE_FORMAT.toPattern()) // use ISO-8601 date format
.create();
String bufferString = "";
int size = input.available();
byte[] buffer = new byte[size];
input.read(buffer);
input.close();
bufferString = new String(buffer);
Build[] builds = gson.fromJson(bufferString, Build[].class);
ArrayList<Build> result = new ArrayList<Build>(Arrays.asList(builds));
return result;
}
项目:sbc-qsystem
文件:NetCommander.java
/**
* Получение недельной таблици с данными для предварительной записи.
*
* @param netProperty netProperty параметры соединения с сервером.
* @param serviceId услуга, в которую пытаемся встать.
* @param date первый день недели за которую нужны данные.
* @param advancedCustomer ID авторизованного кастомера
* @return класс с параметрами и списком времен
*/
public static RpcGetGridOfWeek.GridAndParams getGridOfWeek(INetProperty netProperty,
long serviceId, Date date, long advancedCustomer) {
QLog.l().logger().info("Получить таблицу");
// загрузим ответ
final CmdParams params = new CmdParams();
params.serviceId = serviceId;
params.date = date.getTime();
params.customerId = advancedCustomer;
final String res;
try {
res = send(netProperty, Uses.TASK_GET_GRID_OF_WEEK, params);
} catch (QException e) {// вывод исключений
throw new ClientException(Locales.locMes("command_error2"), e);
}
final Gson gson = GsonPool.getInstance().borrowGson();
final RpcGetGridOfWeek rpc;
try {
rpc = gson.fromJson(res, RpcGetGridOfWeek.class);
} catch (JsonSyntaxException ex) {
throw new ClientException(Locales.locMes("bad_response") + "\n" + ex.toString());
} finally {
GsonPool.getInstance().returnGson(gson);
}
return rpc.getResult();
}
项目:Android-Router
文件:ValueParserTest.java
@Test
public void check_Json_Map() throws ValueParseException {
A a = ObjGenerator.getA();
String json = new Gson().toJson(a);
Object parse = ValueParser.parse(json, Map.class.getCanonicalName());
assertTrue(parse instanceof Map);
}
项目:spark-cassandra-poc
文件:SparkFileLoaderUtils.java
private JavaRDD<VideoViewEvent> prepareVideoRDD(String localFilePath, SparkContext sparkContext) {
JavaRDD<VideoViewEvent> videoEventRDD = sparkContext.textFile(localFilePath, 2).toJavaRDD()
.map(new Function<String, VideoViewEvent>() {
private static final long serialVersionUID = 1L;
@Override
public VideoViewEvent call(String line) throws Exception {
return new Gson().fromJson(line, VideoViewEvent.class);
}
});
return videoEventRDD;
}
项目:full-javaee-app
文件:Candidates.java
public void setAccountOrigin(AccountOrigin accountOrigin) {
if (accountOrigin != null) {
Gson gson = new Gson();
String json = gson.toJson(accountOrigin);
setAccountOrigin(json);
}
}
项目:mapbox-events-android
文件:TelemetryClientTest.java
@Test
public void sendsTheCorrectBodyPostingAnEvent() throws Exception {
Context mockedContext = mock(Context.class, RETURNS_DEEP_STUBS);
MapboxTelemetry.applicationContext = mockedContext;
TelemetryClient telemetryClient = obtainATelemetryClient("anyAccessToken", "anyUserAgent");
List<Event> theEvent = obtainAnEvent();
Callback mockedCallback = mock(Callback.class);
enqueueMockResponse();
telemetryClient.sendEvents(theEvent, mockedCallback);
ArrayList<Event> events = new ArrayList<>(1);
events.add(theEvent.get(0));
assertRequestBodyEquals(new Gson().toJson(events));
}
项目:daf-cacher
文件:ApiServiceTest.java
@Test
public void testPlotList() throws IOException {
final HttpResponse response = Request.Get("http://localhost:4567/plot/")
.execute()
.returnResponse();
assertTrue(response.getStatusLine().getStatusCode() == 200);
final String body = EntityUtils.toString(response.getEntity());
final Gson gson = new GsonBuilder().create();
List<HTTPClient.Card> cards = gson.fromJson(body, new TypeToken<List<HTTPClient.Card>>() {
}.getType());
assertTrue(!cards.isEmpty());
}
项目:GoalsAndHabits
文件:MainActivity.java
/**
* Saves the habits and profile to local storage, as well
* as attempting to save the data to the elasticsearch server.
*/
private void saveData(){
if (habits.size()>0) {
ElasticSearchController.AddHabitsTask addHabitsTask
= new ElasticSearchController.AddHabitsTask();
Habit[] habitArr = habits.toArray(new Habit[habits.size()]);
addHabitsTask.execute(habitArr);
}
if (profile != null) {
ElasticSearchController.UpdateProfileTask updateProfileTask
= new ElasticSearchController.UpdateProfileTask();
updateProfileTask.execute(profile);
}
//Save to local storage:
try {
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
BufferedWriter out = new BufferedWriter(new OutputStreamWriter(fos));
Gson gson = new Gson();
gson.toJson(habits, out);
out.newLine();
out.write("profile");
out.newLine();
gson.toJson(profile, out);
out.flush();
fos.close();
} catch (IOException e) {
throw new RuntimeException();
}
}
项目:SocEltech
文件:ListStringConverter.java
@Override
public List<String> convertToEntityProperty(String databaseValue) {
if (databaseValue == null) {
return null;
} else {
return new Gson().fromJson(databaseValue, new TypeToken<List<String>>() {}.getType());
}
}
项目:bullet-core
文件:FieldTypeAdapterFactoryTest.java
@Test
public void testDeserializationFail() {
Gson gson = getGSON(getFactory(t -> t.getAsJsonObject().get("bar").getAsString(),
asList("typeA", "A"),
asList("typeB", "B")));
Base deserialized = gson.fromJson(makeJSON(1, "garbage", "a"), Base.class);
Assert.assertNull(deserialized);
}
项目:SlotNSlot_Android
文件:StorageUtil.java
public static void save(String identifier, String key, Object object) {
Gson gson = new Gson();
SharedPreferences pref = MainApplication.getContext().getSharedPreferences(identifier, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putString(key, gson.toJson(object));
editor.apply();
}
项目:https-github.com-hyb1996-NoRootScriptDroid
文件:UpdateChecker.java
private UpdateInfo parse(String json) {
Gson gson = new Gson();
Type type = new TypeToken<UpdateInfo>() {
}.getType();
UpdateInfo result = gson.fromJson(json, type);
Log.i(LOG_TAG, result.toString());
return result;
}
项目:Parallator
文件:MainConfig.java
public static MainConfig getMainConfig() {
File workingDirectory = new File(System.getProperty("user.dir"));
File file = new File(workingDirectory, ".config");
String text = Helper.getTextFromFile(file, Helper.UTF_8);
if (text == null) {
MainConfig config = new MainConfig();
config.save();
return config;
}
return new Gson().fromJson(text, MainConfig.class);
}
项目:DeepImagePreview-Project
文件:TextClassifierTest.java
@Test
public void testGivenSampleDataWhenPredictThenCorrectResultReturned() throws Exception {
// Load test data
Type type = new TypeToken<ArrayList<FoodTestEntry>>() {
}.getType();
Resources resources = InstrumentationRegistry.getContext().getResources();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resources.getAssets().open("sample_classifier_test_data.json")));
ArrayList<FoodTestEntry> foodTestEntries = new Gson().fromJson(bufferedReader, type);
int failed = 0;
// Predict and test
for (FoodTestEntry foodTestEntry : foodTestEntries) {
String textToPredict = foodTestEntry.getText();
boolean isPredictionCorrect = mCut.isFoodRelated(textToPredict) == foodTestEntry.isFood();
if (isPredictionCorrect) {
System.out.println("SUCCESS Predicted [" + textToPredict + "] correctly!");
} else {
failed++;
System.out.println("FAILED Predicted [" + textToPredict + "], expecting [" + foodTestEntry.isFood() + "] but was [" + mCut
.isFoodRelated(textToPredict) + "]");
}
}
if (failed > 0) {
int totalTestSize = foodTestEntries.size();
float failedPerc = (float) failed * totalTestSize / 100f;
fail(failed + " out of " + totalTestSize + " failed [" + failedPerc + "%]");
}
}
项目:xifan
文件:SettingsActivity.java
private void checkUpdate() {
FIR.checkForUpdateInFIR(Constants.Fir.FIR_TOKEN, new VersionCheckCallback() {
@Override
public void onSuccess(String versionJson) {
AppVersionInfoRes appVersionInfo =
new Gson().fromJson(versionJson, AppVersionInfoRes.class);
String firVersion = appVersionInfo.getVersionShort().replaceAll("[.]", "");
String currentVersion = BuildConfig.VERSION_NAME.replaceAll("[.]", "");
if (Integer.parseInt(firVersion) > Integer.parseInt(currentVersion)) {
showAppUpdateDialog(appVersionInfo);
} else {
UIUtils.showOkDialog(getActivity(), getString(R.string.title_check_upate),
getString(R.string.text_not_need_update));
}
}
@Override
public void onFail(Exception exception) {
UIUtils.showToast(getActivity(), getString(R.string.text_check_update_fail));
}
@Override
public void onStart() {
UIUtils.showToast(getActivity(), getString(R.string.text_checking_update));
}
@Override
public void onFinish() {
}
});
}
项目:Mvp-Retrofit-Rxjava-Rxbus
文件:HttpService.java
public static void requsetTest(){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://www.cfycp.com/")
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())// 添加RxJava2的适配器支持
.build();
Api api = retrofit.create(Api.class);
api.getText()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Subscriber<List<AllBankListBean>>() {
@Override
public void onSubscribe(Subscription s) {
s.request(Long.MAX_VALUE);
}
@Override
public void onNext(List<AllBankListBean> acticleBean) {
Log.i("HttpService",acticleBean.get(0).getReturnCode());
}
@Override
public void onError(Throwable t) {
Log.e("HttpService",t.getMessage());
}
@Override
public void onComplete() {
Log.e("HttpService","onComplete");
}
});
}
项目:NoRiskNoFun
文件:AssetLoaderMapTests.java
@Test
public void loadingMapWithoutVerticesGivesNull() {
// given
AssetLoaderMap target = new AssetLoaderMap();
GameMap map = createGameMap();
// when
map.vertices.clear();
Asset obtained = target.load(new ByteArrayInputStream(new Gson().toJson(map).getBytes()));
// then
assertThat(obtained, is(nullValue()));
}
项目:react-native-android-library-humaniq-api
文件:WalletMockWebTest.java
@Test public void testGetBalance() throws IOException, InterruptedException {
server = new MockWebServer();
server.enqueue(new MockResponse().setBody("{"
+ " \"success\": true,"
+ " \"data\": {"
+ " \"token\": {"
+ " \"currency\": \"HMQ\","
+ " \"amount\": 190.6"
+ " },"
+ " \"default\": {"
+ " \"currency\": \"USD\","
+ " \"amount\": 27.7323"
+ " },"
+ " \"local\": {"
+ " \"currency\": \"SOS\","
+ " \"amount\": 15141.841623783"
+ " }"
+ " }"
+ "}"));
URL url = server.url("/").url();
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestProperty("Accept-Language", "en-US");
InputStream in = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
assertEquals(HttpURLConnection.HTTP_OK, connection.getResponseCode());
Balance balance = new Gson().fromJson(reader.readLine(), Balance.class);
assertTrue(balance != null);
RecordedRequest request = server.takeRequest();
assertEquals("GET / HTTP/1.1", request.getRequestLine());
assertEquals("en-US", request.getHeader("Accept-Language"));
//System.out.println(server.takeRequest().);
}
项目:retrofit2-synchronous-adapter
文件:SynchronousGsonConverterFactoryTest.java
@Before public void setUp() {
Gson gson = new GsonBuilder()
.registerTypeAdapter(AnInterface.class, new AnInterfaceAdapter())
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(server.url("/"))
.addConverterFactory(GsonConverterFactory.create(gson))
.addCallAdapterFactory(SynchronousCallAdapterFactory.create()) // Add synchronous adapter
.build();
service = retrofit.create(Service.class);
}
项目:scmt-server
文件:DeskClient.java
private Gson createGson() {
return new GsonBuilder()
.registerTypeAdapter(Date.class, new ISO8601DateAdapter())
.registerTypeAdapter(CaseLock.class, CaseLock.TYPE_ADAPTER)
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.create();
}
项目:Byter
文件:PerformanceTimer.java
/**
* Write the evaluated data to a file.
* @param outFile file to write to
* @param map evaluated map with data from measurements.
*/
public void writeEvaluationToFile(final File outFile, final Map<String, Float> map){
final GsonBuilder gsonBuilder = new GsonBuilder();
//register bigDecimal typer for no scientific value printing
gsonBuilder.registerTypeAdapter(Float.class, new JsonSerializer<Float>() {
@Override
public JsonElement serialize(final Float src, final Type typeOfSrc, final JsonSerializationContext context) {
try{
final BigDecimal bigValue = BigDecimal.valueOf(src);
return new JsonPrimitive(bigValue.toPlainString());
}catch (final NumberFormatException nfe){
log.log(Level.INFO,map.toString());
log.log(Level.WARNING, "NumberFormatException during serialize. Number: " + src);
return new JsonPrimitive(src);
}
}
});
final Gson gson = gsonBuilder.setPrettyPrinting().create();
final String json = gson.toJson(map);
//write file to disc
try(
final BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(outFile))
){
outputStream.write(json.getBytes());
outputStream.flush();
} catch (IOException e) {
log.log(Level.WARNING,"IO Exception writing evaluation to disc",e);
}
}
项目:YouTube-Thumbnail-View
文件:OembedVideoInfoDownloader.java
@Override
@NonNull
public VideoInfo download(@NonNull String url, int minThumbnailWidth) throws IOException {
final String encodedUrl = URLEncoder.encode(url, "UTF-8");
final String ombedUrl = "http://www.youtube.com/oembed?url=" + encodedUrl + "&format=json";
final OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url(ombedUrl)
.build();
final Response response = client.newCall(request).execute();
try {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
final Gson gson = new Gson();
final OembedResponse result = gson.fromJson(response.body().charStream(), OembedResponse.class);
if (result.title == null && result.thumbnail_url == null) {
throw new IOException("Invalid youtube oembed response.");
}
return new VideoInfo(result.title, result.thumbnail_url, 0);
}
finally {
response.close();
}
}
项目:TalentZzzz
文件:Config.java
public static void load() {
File yml = new File(Talent.instance.getDataFolder(), "config.yml");
if (!yml.exists())
Talent.instance.saveResource("config.yml", true);
try {
Map map = (Map) new Yaml().load(Files.toString(yml, Charset.forName("utf-8")));
instance = new Gson().fromJson(new Gson().toJson(map), Config.class);
} catch (IOException e) {
e.printStackTrace();
}
}