当前位置: 首页>>代码示例>>Java>>正文


Java Gson类代码示例

本文整理汇总了Java中com.google.gson.Gson的典型用法代码示例。如果您正苦于以下问题:Java Gson类的具体用法?Java Gson怎么用?Java Gson使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


Gson类属于com.google.gson包,在下文中一共展示了Gson类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: apiTagsCreate

import com.google.gson.Gson; //导入依赖的package包/类
/**
 * 创建用户标签
 * 
 * @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;
}
 
开发者ID:AlexLee-CN,项目名称:weixin_api,代码行数:27,代码来源:MpUserApi.java

示例2: getData

import com.google.gson.Gson; //导入依赖的package包/类
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() {
            }
        });
    }
 
开发者ID:mangestudio,项目名称:GCSApp,代码行数:27,代码来源:IntroducePresenter.java

示例3: performSerializeTests

import com.google.gson.Gson; //导入依赖的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);
    }
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:22,代码来源:MainActivity.java

示例4: getPairedDeviceMicroBit

import com.google.gson.Gson; //导入依赖的package包/类
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;
}
 
开发者ID:Samsung,项目名称:microbit,代码行数:22,代码来源:BluetoothUtils.java

示例5: testDeserializationWithMultipleTypes

import com.google.gson.Gson; //导入依赖的package包/类
@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);
}
 
开发者ID:sap-nocops,项目名称:Jerkoff,代码行数:20,代码来源:GraphAdapterBuilderTest.java

示例6: danMuAdd

import com.google.gson.Gson; //导入依赖的package包/类
@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;
}
 
开发者ID:lslxy1021,项目名称:DYB,代码行数:24,代码来源:DMController.java

示例7: replace

import com.google.gson.Gson; //导入依赖的package包/类
/**
 * 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;
    }
}
 
开发者ID:jthomperoo,项目名称:Forge,代码行数:31,代码来源:FileManager.java

示例8: getJsonObject

import com.google.gson.Gson; //导入依赖的package包/类
/**
 * 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;
}
 
开发者ID:ccrama,项目名称:Slide-RSS,代码行数:37,代码来源:HttpUtil.java

示例9: RemoteCommentService

import com.google.gson.Gson; //导入依赖的package包/类
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();
    }
 
开发者ID:jshvarts,项目名称:OfflineSampleApp,代码行数:20,代码来源:RemoteCommentService.java

示例10: loadProfileInformation

import com.google.gson.Gson; //导入依赖的package包/类
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());

    }
 
开发者ID:Amay-Mishra,项目名称:Trackr,代码行数:19,代码来源:MainMenuActivity.java

示例11: rxCreateDiskObservable

import com.google.gson.Gson; //导入依赖的package包/类
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());
}
 
开发者ID:ynztlxdeai,项目名称:TextReader,代码行数:22,代码来源:RxUtil.java

示例12: extractEmptyBranchTest

import com.google.gson.Gson; //导入依赖的package包/类
@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());
    }


}
 
开发者ID:hermannpencole,项目名称:nifi-config,代码行数:24,代码来源:ExtractProcessorServiceTest.java

示例13: convertJSON

import com.google.gson.Gson; //导入依赖的package包/类
@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();
}
 
开发者ID:838030195,项目名称:DaiGo,代码行数:18,代码来源:Order.java

示例14: provideRedditResource

import com.google.gson.Gson; //导入依赖的package包/类
@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);
}
 
开发者ID:Syntactec,项目名称:subreddify-android,代码行数:17,代码来源:PollerModule.java

示例15: getBadges

import com.google.gson.Gson; //导入依赖的package包/类
@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()]);
}
 
开发者ID:PizzaCrust,项目名称:Roblox4j,代码行数:18,代码来源:BasicRobloxian.java


注:本文中的com.google.gson.Gson类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。