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


Java GsonBuilder类代码示例

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


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

示例1: propagateGsonAttributes

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@Test
public void propagateGsonAttributes() {
  Gson gson = new GsonBuilder()
      .serializeNulls()
      .disableHtmlEscaping()
      .setPrettyPrinting()
      .create();

  GsonOptions options = new GsonOptions(gson, true);
  JsonReader reader = new JsonReader(new StringReader(""));
  options.setReaderOptions(reader);

  check(reader.isLenient());

  JsonWriter writer = new JsonWriter(new StringWriter());
  options.setWriterOptions(writer);

  check(writer.isLenient());
  check(!writer.isHtmlSafe());
  check(writer.getSerializeNulls());

  // checks pretty printing
  check(gson.toJson(Collections.singletonMap("k", "v"))).is("{\n  \"k\": \"v\"\n}");
}
 
开发者ID:weiwenqiang,项目名称:GitHub,代码行数:25,代码来源:JaxrsTest.java

示例2: addGroup

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@RequestMapping(value = "/v1/dispatch/batch/define/group", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "在批次中添加任务组")
public String addGroup(HttpServletResponse response, HttpServletRequest request) {
    String batchId = request.getParameter("batch_id");
    String domainId = request.getParameter("domain_id");
    String json = request.getParameter("JSON");
    List<BatchGroupDto> list = new GsonBuilder().create().fromJson(json, new TypeToken<List<BatchGroupDto>>() {
    }.getType());

    for (BatchGroupDto m : list) {
        m.setDomainId(domainId);
        m.setBatchId(batchId);
    }

    RetMsg retMsg = batchGroupService.addGroup(list);
    if (!retMsg.checkCode()) {
        response.setStatus(retMsg.getCode());
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
 
开发者ID:hzwy23,项目名称:batch-scheduler,代码行数:23,代码来源:BatchGroupRelController.java

示例3: getVocab

import com.google.gson.GsonBuilder; //导入依赖的package包/类
public Set<String> getVocab(String vocabDataFile) throws IOException {
    RuntimeTypeAdapterFactory<DASTNode> nodeAdapter = RuntimeTypeAdapterFactory.of(DASTNode.class, "node")
            .registerSubtype(DAPICall.class)
            .registerSubtype(DBranch.class)
            .registerSubtype(DExcept.class)
            .registerSubtype(DLoop.class)
            .registerSubtype(DSubTree.class);
    Gson gson = new GsonBuilder().serializeNulls()
            .registerTypeAdapterFactory(nodeAdapter)
            .create();
    String s = new String(Files.readAllBytes(Paths.get(vocabDataFile)));
    VocabData js = gson.fromJson(s, VocabData.class);

    Set<String> vocab = new HashSet<>();
    for (VocabDataPoint dataPoint: js.programs) {
        DSubTree ast = dataPoint.ast;
        Set<DAPICall> apicalls = ast.bagOfAPICalls();
        vocab.addAll(apicalls.stream().map(c -> c.toString()).collect(Collectors.toSet()));
    }
    return vocab;
}
 
开发者ID:capergroup,项目名称:bayou,代码行数:22,代码来源:DataSanityChecker.java

示例4: testRec

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@Test
public void testRec() {
    try {
        GsonBuilder gsonBuilder = new GsonBuilder();
        // register custom adapter from configuration
        new GraphAdapterBuilder().addType(A.class).addType(B.class).registerOn(gsonBuilder);
        // gsonBuilder.registerTypeHierarchyAdapter(Object.class,
        // new ObjectSerializer(gsonBuilder.create()));
        // gsonBuilder.registerTypeHierarchyAdapter(Object.class,
        // new ObjectDeserializer(gsonBuilder.create()));
        Gson gson = gsonBuilder.create();

        A a = new A();
        B b = new B();
        a.setB(b);
        b.setA(a);

        String json = gson.toJson(a);
        LOG.info("json: " + json);
        A a2 = gson.fromJson(json, a.getClass());
        LOG.info("a: " + a2);

    } catch (Exception e) {
        LOG.error(e);
    }
}
 
开发者ID:sap-nocops,项目名称:Jerkoff,代码行数:27,代码来源:GsonTest.java

示例5: testSerializeListOfLists

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@Test
public void testSerializeListOfLists() {
    Type listOfListsType = new TypeToken<List<List<?>>>() {
    }.getType();
    Type listOfAnyType = new TypeToken<List<?>>() {
    }.getType();

    List<List<?>> listOfLists = new ArrayList<List<?>>();
    listOfLists.add(listOfLists);
    listOfLists.add(new ArrayList<Object>());

    GsonBuilder gsonBuilder = new GsonBuilder();
    new GraphAdapterBuilder().addType(listOfListsType).addType(listOfAnyType)
            .registerOn(gsonBuilder);
    Gson gson = gsonBuilder.create();

    String json = gson.toJson(listOfLists, listOfListsType);
    assertEquals("{'0x1':['0x1','0x2'],'0x2':[]}", json.replace('"', '\''));
}
 
开发者ID:sap-nocops,项目名称:Jerkoff,代码行数:20,代码来源:GraphAdapterBuilderTest.java

示例6: setCommand

import com.google.gson.GsonBuilder; //导入依赖的package包/类
/**
 * Insert a new {@link CustomCommand} in the {@link DBCustomCommand} synchronising with a basic
 * lock object in a vain attempt to prevent concurrency issues.
 *
 * @param ctx           the application context
 * @param customCommand to be set
 * @return true if the insertion was successful
 */
public static Pair<Boolean, Long> setCommand(@NonNull final Context ctx, @NonNull final CustomCommand customCommand,
                                             final long rowId) {

    synchronized (lock) {

        final Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        final String gsonString = gson.toJson(customCommand);

        final DBCustomCommand dbCustomCommand = new DBCustomCommand(ctx);

        final Pair<Boolean, Long> duplicatePair;
        if (rowId > -1) {
            duplicatePair = new Pair<>(true, rowId);
        } else {
            duplicatePair = commandExists(dbCustomCommand, customCommand);
        }

        return dbCustomCommand.insertPopulatedRow(customCommand.getKeyphrase(),
                customCommand.getRegex(), gsonString, duplicatePair.first, duplicatePair.second);
    }
}
 
开发者ID:brandall76,项目名称:Saiy-PS,代码行数:30,代码来源:CustomCommandHelper.java

示例7: time

import com.google.gson.GsonBuilder; //导入依赖的package包/类
private void time() {
    String srcData = readAssetsFile("goods.json");
    srcDataText.setText(srcData);
    Gson gson = new GsonBuilder().create();
    int count = 10000;

    long start = SystemClock.elapsedRealtime();
    for (int i = 0; i < count; i++) {
        Goods goods = Goods$$CREATOR.create(srcData, false);
    }
    long end = SystemClock.elapsedRealtime();
    long selfTime = end - start;


    start = SystemClock.elapsedRealtime();
    for (int i = 0; i < count; i++) {
        gson.fromJson(srcData, Goods.class);
    }

    end = SystemClock.elapsedRealtime();
    dstDataText.setText(String.format("LimitJSON time: %d\n Gson Time: %d", selfTime, (end - start)));
}
 
开发者ID:freelifer,项目名称:limitjson,代码行数:23,代码来源:VerificationActivity.java

示例8: createBooksAPI

import com.google.gson.GsonBuilder; //导入依赖的package包/类
private BooksAPI createBooksAPI(boolean withKey, boolean withToken) {
    HttpLoggingInterceptor logger = new HttpLoggingInterceptor();
    logger.setLevel(HttpLoggingInterceptor.Level.BODY);

    OkHttpClient.Builder clientBuilder = new OkHttpClient().newBuilder();
    if (withKey) clientBuilder.addInterceptor(authRepo.getApiKeyInterceptor());
    if (withToken) clientBuilder.addInterceptor(authRepo.getAccessTokenInterceptor());
    if (true) clientBuilder.addInterceptor(logger);

    OkHttpClient client = clientBuilder.build();

    Gson gson = new GsonBuilder().setLenient().create();
    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BOOKS_URL_BASE)
            .client(client)
            .addConverterFactory(GsonConverterFactory.create(gson))
            .build();

    return retrofit.create(BooksAPI.class);
}
 
开发者ID:approov,项目名称:AppAuth-OAuth2-Books-Demo,代码行数:21,代码来源:BooksRepo.java

示例9: save

import com.google.gson.GsonBuilder; //导入依赖的package包/类
public void save() {
    this.removeExpired();

    try {
        File file = new File(this.file);
        if (!file.exists()) {
            file.createNewFile();
        }

        LinkedList<LinkedHashMap<String, String>> list = new LinkedList<>();
        for (BanEntry entry : this.list.values()) {
            list.add(entry.getMap());
        }
        Utils.writeFile(this.file, new ByteArrayInputStream(new GsonBuilder().setPrettyPrinting().create().toJson(list).getBytes(StandardCharsets.UTF_8)));
    } catch (IOException e) {
        MainLogger.getLogger().error("Could not save ban list ", e);
    }
}
 
开发者ID:Rsplwe,项目名称:Nukkit-Java9,代码行数:19,代码来源:BanList.java

示例10: testReadWrite

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@Test
public void testReadWrite() throws IOException {
  DefinitionModel model1 = new DefinitionModel(TEST_DEF1);
  model1.addDefinition(new ExpectedModel(OBJECT2));
  model1.addDefinition(new InstanceModel(OBJECT1, TEST_DEF1, OBJECT1_SOURCE, TYPE_STRING,
      Arrays.asList(new InstanceDependencyModel(OBJECT2, TYPE_STRING)), Arrays.asList()));
  DefinitionModel model2 = new DefinitionModel(TEST_DEF2);
  model2.addDependencyNames(TEST_DEF1);
  model2.addDefinition(new InstanceModel(OBJECT2, TEST_DEF2, OBJECT2_SOURCE, TYPE_STRING, Arrays.asList(), Arrays.asList()));
  Gson gson = new GsonBuilder().create();
  String output = gson.toJson(model1);
  System.out.println(output);
  DefinitionModel model1FromJson = gson.fromJson(output, DefinitionModel.class);
  //TODO: assert more, or implement a real equals/hash methods for these classes.
  assertThat(model1.getExpectedDefinitions().get(0).getIdentity())
    .isEqualTo(model1FromJson.getExpectedDefinitions().get(0).getIdentity());    
}
 
开发者ID:salesforce,项目名称:AptSpring,代码行数:18,代码来源:TestReadWrite.java

示例11: createDefaultAdapter

import com.google.gson.GsonBuilder; //导入依赖的package包/类
public void createDefaultAdapter() {
  Gson gson = new GsonBuilder()
    .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
    .registerTypeAdapter(DateTime.class, new DateTimeTypeAdapter())
    .registerTypeAdapter(LocalDate.class, new LocalDateTypeAdapter())
    .create();

  okBuilder = new OkHttpClient.Builder();

  String baseUrl = "https://api.us-east-1.mbedcloud.com";
  if(!baseUrl.endsWith("/"))
    baseUrl = baseUrl + "/";

  adapterBuilder = new Retrofit
    .Builder()
    .baseUrl(baseUrl)
    .addConverterFactory(ScalarsConverterFactory.create())
    .addConverterFactory(GsonCustomConverterFactory.create(gson));
}
 
开发者ID:ARMmbed,项目名称:mbed-cloud-sdk-java,代码行数:20,代码来源:ApiClient.java

示例12: sendDataToFlume

import com.google.gson.GsonBuilder; //导入依赖的package包/类
public void sendDataToFlume(VideoViewEvent data) {
	JSONEvent jsonEvent = new JSONEvent();
	HashMap<String, String> headers = new HashMap<String, String>();

	Gson gson = new GsonBuilder().create();

	jsonEvent.setHeaders(headers);
	jsonEvent.setBody(gson.toJson(data).getBytes());

	// Send the event
	try {
		client.append(jsonEvent);
	} catch (EventDeliveryException e) {
		e.printStackTrace();
	}
}
 
开发者ID:alokawi,项目名称:spark-cassandra-poc,代码行数:17,代码来源:FlumeDataWriter.java

示例13: batchAuth

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@RequestMapping(value = "/auth/batch", method = RequestMethod.POST)
public String batchAuth(HttpServletResponse response, HttpServletRequest request) {
    String modifyUserId = JwtService.getConnUser(request).getUserId();
    String json = request.getParameter("JSON");
    List<UserRoleEntity> list = new GsonBuilder().create().fromJson(json,
            new TypeToken<List<UserRoleEntity>>() {
            }.getType());
    try {
        int size = roleService.batchAuth(list, modifyUserId);
        if (1 == size) {
            return Hret.success(200, "success", null);
        }
        response.setStatus(422);
        return Hret.error(422, "授权失败,用户已经拥有了这个角色", null);
    } catch (Exception e) {
        logger.info(e.getMessage());
        response.setStatus(421);
        return Hret.error(421, "授权失败,用户已经拥有了这个角色", null);
    }
}
 
开发者ID:hzwy23,项目名称:batch-scheduler,代码行数:21,代码来源:RoleController.java

示例14: seedDatabaseQuestions

import com.google.gson.GsonBuilder; //导入依赖的package包/类
@Override
public Observable<Boolean> seedDatabaseQuestions() {

    GsonBuilder builder = new GsonBuilder().excludeFieldsWithoutExposeAnnotation();
    final Gson gson = builder.create();

    return mDbHelper.isQuestionEmpty()
            .concatMap(new Function<Boolean, ObservableSource<? extends Boolean>>() {
                @Override
                public ObservableSource<? extends Boolean> apply(Boolean isEmpty)
                        throws Exception {
                    if (isEmpty) {
                        Type type = $Gson$Types
                                .newParameterizedTypeWithOwner(null, List.class,
                                        Question.class);
                        List<Question> questionList = gson.fromJson(
                                CommonUtils.loadJSONFromAsset(mContext,
                                        AppConstants.SEED_DATABASE_QUESTIONS),
                                type);

                        return saveQuestionList(questionList);
                    }
                    return Observable.just(false);
                }
            });
}
 
开发者ID:MindorksOpenSource,项目名称:android-mvvm-architecture,代码行数:27,代码来源:AppDataManager.java

示例15: attemptLogin

import com.google.gson.GsonBuilder; //导入依赖的package包/类
private void attemptLogin(Map<String, String> argMap)
{
    YggdrasilUserAuthentication auth = (YggdrasilUserAuthentication) new YggdrasilAuthenticationService(Proxy.NO_PROXY, "1").createUserAuthentication(Agent.MINECRAFT);
    auth.setUsername(argMap.get("username"));
    auth.setPassword(argMap.get("password"));
    argMap.put("password", null);

    try {
        auth.logIn();
    }
    catch (AuthenticationException e)
    {
        LOGGER.error("-- Login failed!  " + e.getMessage());
        Throwables.propagate(e);
        return; // dont set other variables
    }

    LOGGER.info("Login Succesful!");
    argMap.put("accessToken", auth.getAuthenticatedToken());
    argMap.put("uuid", auth.getSelectedProfile().getId().toString().replace("-", ""));
    argMap.put("username", auth.getSelectedProfile().getName());
    argMap.put("userType", auth.getUserType().getName());
    
    // 1.8 only apperantly.. -_-
    argMap.put("userProperties", new GsonBuilder().registerTypeAdapter(PropertyMap.class, new PropertyMap.Serializer()).create().toJson(auth.getUserProperties()));
}
 
开发者ID:F1r3w477,项目名称:CustomWorldGen,代码行数:27,代码来源:GradleStart.java


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