@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); }
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; }
@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); } }
@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}"); }
@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('"', '\'')); }
/** * 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); } }
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))); }
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); }
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); } }
@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()); }
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)); }
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(); } }
@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); } }
@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); } }); }
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())); }
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() { } }); }
@Provides @Singleton public Gson provideGson() { GsonBuilder builder = new GsonBuilder(); builder.setLenient(); builder.registerTypeAdapter(Date.class, (JsonDeserializer<Date>) (json, typeOfT, context) -> { if (json.getAsJsonPrimitive().isNumber()) { return new Date(json.getAsJsonPrimitive().getAsLong() * 1000); } else { return null; } }); return builder.create(); }
/** * {@inheritDoc} */ @Override public String serialize() { final GsonBuilder builder = new GsonBuilder(); builder.excludeFieldsWithoutExposeAnnotation(); builder.disableHtmlEscaping(); final Gson gson = builder.create(); return gson.toJson(this); }
private Gson makeGson() { return new GsonBuilder() .setLenient() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'") .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES) .create(); }
@Override public void saveFilledAutofillFieldCollection(Context context, FilledAutofillFieldCollection filledAutofillFieldCollection) { String datasetName = "dataset-" + getDatasetNumber(context); filledAutofillFieldCollection.setDatasetName(datasetName); Set<String> allAutofillData = getAllAutofillDataStringSet(context); Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); allAutofillData.add(gson.toJson(filledAutofillFieldCollection)); saveAllAutofillDataStringSet(context, allAutofillData); incrementDatasetNumber(context); }
/** * Gets a list of recently used Learning Designs for currently logged in user. */ public ActionForward getLearningDesignAccess(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { Integer userId = getUserId(); List<LearningDesignAccess> accessList = getAuthoringService().updateLearningDesignAccessByUser(userId); accessList = accessList.subList(0, Math.min(accessList.size(), AuthoringAction.LEARNING_DESIGN_ACCESS_ENTRIES_LIMIT - 1)); Gson gson = new GsonBuilder().create(); response.setContentType("application/json;charset=utf-8"); response.getWriter().write(gson.toJson(accessList)); return null; }
public static void main(String[] args) throws IOException, ParseException { configureLog(); if (args.length != 1) { System.out.println("Usage: main <apk path>"); System.exit(-1); } String apkPath = args[0]; GsonBuilder gsonBuilder = new GsonBuilder(); JsonSerializer<TObjectIntMap> serializer = (src, typeOfSrc, context) -> { JsonObject jsonMerchant = new JsonObject(); for (Object key : src.keys()) { int value = src.get(key); jsonMerchant.addProperty(key.toString(), value); } return jsonMerchant; }; gsonBuilder.registerTypeAdapter(TObjectIntMap.class, serializer); Gson gson = gsonBuilder .disableHtmlEscaping() .serializeSpecialFloatingPointValues() .setExclusionStrategies(new JarFileExclusionStrategy()) .setPrettyPrinting() .create(); Writer writer = new OutputStreamWriter(System.out); ApkFile apkFile = new ApkFile(apkPath, true, true, true, true, false); gson.toJson(apkFile, writer); writer.close(); apkFile.close(); }
public UserList(File saveFile) { this.saveFile = saveFile; GsonBuilder gsonbuilder = (new GsonBuilder()).setPrettyPrinting(); gsonbuilder.registerTypeHierarchyAdapter(UserListEntry.class, new UserList.Serializer()); this.gson = gsonbuilder.create(); }
public static ActivityList getActivityList(Context context) throws Exception { String result = Connector.getDataByGet(UPDATE_JSON_URL, "utf-8"); JSONObject jObject = new JSONObject(result); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); ActivityList activity_list = gson.fromJson(jObject.getJSONArray("data") .toString(), ActivityList.class); cleanCacheDir(context); for (ActivityInfo activity : activity_list) { downloadActivityImage(context, activity.getImage()); } return activity_list; }
@Override public void flush() throws IOException { for (String domain : domainConfigMap.keySet()) { File file = new File(configFolder, domain); if (!file.exists()) file.createNewFile(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); gson.toJson(domainConfigMap.get(domain), new FileWriter(file)); } }
/** * Parse order request from mobile API */ public static UpdateOrderRequest updateOrderInputFromJson(String jsonString) { final GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.setDateFormat(Constants.DATE_FORMAT) .serializeNulls().create(); return gson.fromJson(jsonString, UpdateOrderRequest.class); }
/** * Save the Saiy account list to the shared preferences * * @param ctx the application context * @param accountList the {@link SaiyAccountList} */ public static boolean saveSaiyAccountList(@NonNull final Context ctx, @NonNull final SaiyAccountList accountList) { if (DEBUG) { MyLog.i(CLS_NAME, "saveSaiyAccountList"); } if (accountList.size() > 0) { final Gson gson = new GsonBuilder().disableHtmlEscaping().create(); final String gsonString = gson.toJson(encode(accountList)); if (DEBUG) { MyLog.i(CLS_NAME, "saveSaiyAccountList: gsonString: " + gsonString); } SPH.setSaiyAccounts(ctx, gsonString); } else { if (DEBUG) { MyLog.i(CLS_NAME, "saveSaiyAccountList empty"); } SPH.setSaiyAccounts(ctx, null); } return true; }
@Provides @AppScope Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); }
public static void main(String... args) throws IOException { MockWebServer server = new MockWebServer(); server.start(); server.enqueue(new MockResponse().setBody("{\"name\": \"Moshi\"}")); server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}")); server.enqueue(new MockResponse().setBody("<user name=\"SimpleXML\"/>")); server.enqueue(new MockResponse().setBody("{\"name\": \"Gson\"}")); com.squareup.moshi.Moshi moshi = new com.squareup.moshi.Moshi.Builder().build(); com.google.gson.Gson gson = new GsonBuilder().create(); MoshiConverterFactory moshiConverterFactory = MoshiConverterFactory.create(moshi); GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson); SimpleXmlConverterFactory simpleXmlConverterFactory = SimpleXmlConverterFactory.create(); Retrofit retrofit = new Retrofit.Builder().baseUrl(server.url("/")) .addConverterFactory( new AnnotatedConverterFactory.Builder().add(Moshi.class, moshiConverterFactory) .add(Gson.class, gsonConverterFactory) .add(SimpleXml.class, simpleXmlConverterFactory) .build()) .addConverterFactory(gsonConverterFactory) .build(); Service service = retrofit.create(Service.class); Library library1 = service.exampleMoshi().execute().body(); System.out.println("Library 1: " + library1.name); Library library2 = service.exampleGson().execute().body(); System.out.println("Library 2: " + library2.name); Library library3 = service.exampleSimpleXml().execute().body(); System.out.println("Library 3: " + library3.name); Library library4 = service.exampleDefault().execute().body(); System.out.println("Library 4: " + library4.name); server.shutdown(); }
@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)) .build(); service = retrofit.create(Service.class); }
@GET @Path("/search") @Produces(MediaType.APPLICATION_JSON) @Consumes("text/plain") public Response searchMetadata(@QueryParam("query") String query, @QueryParam("operator") String operator, @QueryParam("rankoption") String rankoption) { Properties config = mEngine.getConfig(); String fileList = searcher .ssearch(config.getProperty(MudrodConstants.ES_INDEX_NAME), config.getProperty(MudrodConstants.RAW_METADATA_TYPE), query, operator, //please replace it with and, or, phrase rankoption, ranker); Gson gson = new GsonBuilder().create(); String json = gson.toJson(gson.fromJson(fileList, JsonObject.class)); LOG.debug("Response received: {}", json); return Response.ok(json, MediaType.APPLICATION_JSON).build(); }
@Provides @Singleton static Gson provideGson() { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES); return gsonBuilder.create(); }
/** * the fully configured gson instance. * @return the gson instanse */ @Value.Default public Gson gson() { GsonBuilder gsonBuilder = new GsonBuilder(); for (TypeAdapterFactory factory : ServiceLoader.load(TypeAdapterFactory.class)) { gsonBuilder.registerTypeAdapterFactory(factory); } return gsonBuilder.create(); }
@Test public void sendsTheCorrectBodyPostingNavigationArriveEvent() throws Exception { TelemetryClient telemetryClient = obtainATelemetryClient("anyAccessToken", "anyUserAgent"); Event.Type arrive = Event.Type.NAV_ARRIVE; Event anArriveEvent = obtainNavigationEvent(arrive); List<Event> theArriveEvent = obtainEvents(anArriveEvent); Callback mockedCallback = mock(Callback.class); enqueueMockResponse(); telemetryClient.sendEvents(theArriveEvent, mockedCallback); GsonBuilder gsonBuilder = configureTypeAdapter(arrive, new GsonBuilder()); String expectedRequestBody = obtainExpectedRequestBody(gsonBuilder, theArriveEvent.get(0)); assertRequestBodyEquals(expectedRequestBody); }
@Test public void deserialize_bbox(){ GsonBuilder gsonBuilder = new GsonBuilder(); Gson gson = gsonBuilder.create(); double[] bbox = gson.fromJson("[-10.0, -10.0, 10.0, 10.0]", double[].class); assertThat(bbox[0], equalTo(-10.0)); assertThat(bbox[2], equalTo(10.0)); assertThat(bbox[3], equalTo(10.0)); }
public VariantProvider () { logger.debug ( "Created instance" ); this.builder = new GsonBuilder (); this.builder.registerTypeAdapter ( Variant.class, new VariantJsonSerializer () ); this.builder.registerTypeAdapter ( Variant.class, new VariantJsonDeserializer () ); }
private void loadModel(File file) throws ModelFormatException { try { FileInputStream stream = new FileInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); String str = ""; String line; while ((line = reader.readLine()) != null) { str = str + line + "\n"; } reader.close(); GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(JsonJsonModel.class, new Deserializer()); Gson gson = builder.create(); model = gson.fromJson(str, JsonJsonModel.class); } catch (Exception e) { e.printStackTrace(); throw new ModelFormatException("Model " + filename + " has something wrong"); } }
private ApiRetrofit() { super(); Gson gson = new GsonBuilder() .setLenient() .create(); //在构造方法中完成对Retrofit接口的初始化 mApi = new Retrofit.Builder() .baseUrl(MyApi.BASE_URL) .client(getClient()) .addConverterFactory(GsonConverterFactory.create(gson)) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build() .create(MyApi.class); }
public static PreferredJourney getNotificationPreferredJourney(Context context) { Gson gson = new GsonBuilder() .registerTypeAdapter(DateTime.class, new DateTimeAdapter()) .registerTypeAdapterFactory(new PostProcessingEnabler()) .create(); return gson.fromJson(getSharedPreferenceObject(context, SP_NOTIFICATION_PREF_JOURNEY), PreferredJourney.class); }