com.google.gson.Gson Java Examples
The following examples show how to use
com.google.gson.Gson.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DataManager.java From ETSMobile-Android2 with Apache License 2.0 | 8 votes |
private DataManager() { dbHelper = new DatabaseHelper(c); moodleService = new Retrofit.Builder() .baseUrl(c.getString(R.string.moodle_url)) .client(TLSUtilities.createETSOkHttpClient(c)) .addConverterFactory(GsonConverterFactory.create()) .build() .create(MoodleWebService.class); // Notifications dates layout are different for MonÉTS Gson monETSGson = new GsonBuilder() .setDateFormat("yyyy-MM-dd'T'HH:mm:ss") .create(); monETSService = new Retrofit.Builder() .baseUrl(c.getString(R.string.url_mon_ets)) .client(TLSUtilities.createETSOkHttpClient(c)) .addConverterFactory(GsonConverterFactory.create(monETSGson)) .build() .create(MonETSWebService.class); }
Example #2
Source File: BgaAllActivity.java From AndroidAnimationExercise with Apache License 2.0 | 7 votes |
private void initData() { String json = Tools.readStrFromAssets("school.json", mContext); Gson mGson = new Gson(); List<SchoolBeanShell> mBeanShells = mGson.fromJson(json, new TypeToken<ArrayList<SchoolBeanShell>>() { }.getType()); for (int i = 0; i < mBeanShells.size(); i++) { locations.add(mBeanShells.get(i).getName()); } mContentAdapter.setData(locations); json = Tools.readStrFromAssets("pics.json", mContext); List<String> pics = mGson.fromJson(json, new TypeToken<List<String>>() { }.getType()); mBGABanner.setData(pics.subList(0, 4), locations.subList(0, 4)); }
Example #3
Source File: TestJSONObj.java From nuls-v2 with MIT License | 6 votes |
/** * alpha3 */ public List<AccountData> readStream() { List<AccountData> accountDataList = new ArrayList<>(); try { //方式一:将文件放入Transaction模块test的resources中,json格式 只保留list部分 InputStream inputStream = getClass().getClassLoader().getResource("alpha2.json").openStream(); //方式二:定义文件目录 //InputStream inputStream = new FileInputStream("E:/IdeaProjects/nuls_2.0/module/nuls-transaction/src/test/resources/alpha2.json"); JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8")); Gson gson = new GsonBuilder().create(); reader.beginArray(); while (reader.hasNext()) { AccountData accountData = gson.fromJson(reader, AccountData.class); accountDataList.add(accountData); } reader.close(); } catch (Exception e) { e.printStackTrace(); } return accountDataList; }
Example #4
Source File: GetGoodsAttrsAction.java From OnlineShoppingSystem with MIT License | 6 votes |
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SellerService service = new SellerServiceImpl(); int goodsId = 0; String gId = request.getParameter("goodsId"); if (!StringUtil.isEmpty(gId)) goodsId = Integer.parseInt(gId); ArrayList<GoodsAttr> goodsAttrs = service.getAttrs(goodsId); Gson gson = new Gson(); String ga = gson.toJson(goodsAttrs); // System.out.println("属性" + ga); response.setCharacterEncoding("UTF-8"); response.getWriter().append(ga); }
Example #5
Source File: Indexes.java From java-cloudant with Apache License 2.0 | 6 votes |
/** * Utility to list indexes of a given type. * * @param type the type of index to list, null means all types * @param modelType the class to deserialize the index into * @param <T> the type of the index * @return the list of indexes of the specified type */ private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) { List<T> indexesOfType = new ArrayList<T>(); Gson g = new Gson(); for (JsonElement index : indexes) { if (index.isJsonObject()) { JsonObject indexDefinition = index.getAsJsonObject(); JsonElement indexType = indexDefinition.get("type"); if (indexType != null && indexType.isJsonPrimitive()) { JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive(); if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive .getAsString().equals(type))) { indexesOfType.add(g.fromJson(indexDefinition, modelType)); } } } } return indexesOfType; }
Example #6
Source File: DistributedResourcePoolTest.java From zeppelin with Apache License 2.0 | 6 votes |
@Test public void testRemoteDistributedResourcePool() throws InterpreterException { Gson gson = new Gson(); InterpreterResult ret; intp1.interpret("put key1 value1", context); intp2.interpret("put key2 value2", context); ret = intp1.interpret("getAll", context); assertEquals(2, ResourceSet.fromJson(ret.message().get(0).getData()).size()); ret = intp2.interpret("getAll", context); assertEquals(2, ResourceSet.fromJson(ret.message().get(0).getData()).size()); ret = intp1.interpret("get key1", context); assertEquals("value1", gson.fromJson(ret.message().get(0).getData(), String.class)); ret = intp1.interpret("get key2", context); assertEquals("value2", gson.fromJson(ret.message().get(0).getData(), String.class)); }
Example #7
Source File: NativeHostServices.java From org.hl7.fhir.core with Apache License 2.0 | 6 votes |
/** * get back a JSON object with information about the process. * @return */ public String status() { JsonObject json = new JsonObject(); json.addProperty("custom-resource-count", resourceCount); validator.getContext().reportStatus(json); json.addProperty("validation-count", validationCount); json.addProperty("convert-count", convertCount); json.addProperty("unconvert-count", unConvertCount); json.addProperty("exception-count", exceptionCount); synchronized (lock) { json.addProperty("last-exception", lastException); } json.addProperty("mem-max", Runtime.getRuntime().maxMemory() / (1024*1024)); json.addProperty("mem-total", Runtime.getRuntime().totalMemory() / (1024*1024)); json.addProperty("mem-free", Runtime.getRuntime().freeMemory() / (1024*1024)); json.addProperty("mem-used", (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024*1024)); Gson gson = new GsonBuilder().create(); return gson.toJson(json); }
Example #8
Source File: RedisConnectionPoolConfig.java From netty-cookbook with Apache License 2.0 | 6 votes |
public static JedisPoolConfig getJedisPoolConfigInstance(){ if(_instance == null){ try { String json = FileUtils.readFileAsString(getRedisPoolConnectionConfigFile()); _instance = new Gson().fromJson(json, RedisConnectionPoolConfig.class); } catch (Exception e) { if (e instanceof JsonSyntaxException) { e.printStackTrace(); System.err.println("Wrong JSON syntax in file "+getRedisPoolConnectionConfigFile()); } else { e.printStackTrace(); } } } return _instance.getJedisPoolConfig(); }
Example #9
Source File: MyApp.java From nono-android with GNU General Public License v3.0 | 6 votes |
public List<NotificationDataModel> getNotificationDataModelList() { if(notificationDataModelList == null) { SharedPreferences preferences = getSharedPreferences("gloable", Activity.MODE_PRIVATE); String notificationModeListJsonString = preferences.getString("notification_mode_list_json_string",""); if(notificationModeListJsonString==null || notificationModeListJsonString.isEmpty() ) { notificationDataModelList = new ArrayList<>(); return notificationDataModelList; } notificationDataModelList = new Gson().fromJson(notificationModeListJsonString , new TypeToken<List<NotificationDataModel>>(){}.getType()); return notificationDataModelList; } return notificationDataModelList; }
Example #10
Source File: HttpUtil.java From vi with Apache License 2.0 | 6 votes |
public static Map<String, Object> loadPostParams(HttpServletRequest req){ Map<String,Object> params =null; try { Gson gson = new Gson(); Type paraMap = new TypeToken<Map<String, JsonElement>>(){}.getType(); StringBuilder rawJson = new StringBuilder( IOUtils.readAll(req.getInputStream())); if(rawJson.length() == 0){ for(Map.Entry<String, String[]> entry:req.getParameterMap().entrySet()){ rawJson.append(entry.getKey()); if(entry.getValue()[0].length()>0) { rawJson.append("=" ).append(entry.getValue()[0]); } } } params = gson.fromJson(rawJson.toString(),paraMap); } catch (IOException e) { e.printStackTrace(); } return params; }
Example #11
Source File: Reports.java From olca-app with Mozilla Public License 2.0 | 6 votes |
public static void save(Project project, Report report, IDatabase database) { if (report == null || project == null) return; Logger log = LoggerFactory.getLogger(Reports.class); File file = getReportFile(project, database); if (file == null) { log.error("failed to get report file {} for {}" + file, report); return; } if (!file.getParentFile().exists()) file.getParentFile().mkdirs(); log.trace("write report {} to file {}", report, file); try (FileOutputStream fos = new FileOutputStream(file)) { Gson gson = new Gson(); String json = gson.toJson(report); IOUtils.write(json, fos, "utf-8"); } catch (Exception e) { log.error("failed to write report file", e); } }
Example #12
Source File: DiscussionFragment.java From 4pdaClient-plus with Apache License 2.0 | 6 votes |
@Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // recLifeCycle(getClass(), CALL_TO_SUPER); view = inflater.inflate(LAYOUT, container, false); // recLifeCycle(getClass(), RETURN_FROM_SUPER); mModelList = new Gson().fromJson(getArguments().getString(LIST_ARG), new TypeToken<ArrayList<DiscussionModel>>() {}.getType()); if (mModelList.size() != 0) { mRecyclerView = (RecyclerView) view.findViewById(R.id.devDbRecyclerView); mRecyclerView.setVisibility(View.VISIBLE); mAdapter = new DiscussionAdapter(getActivity(), mModelList); mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); mRecyclerView.setAdapter(mAdapter); mAdapter.notifyDataSetChanged(); } else { /*CardView cardView = (CardView) view.findViewById(R.id.dev_db_error_message_con); cardView.setVisibility(View.VISIBLE);*/ TextView textView = ButterKnife.findById(view, R.id.dev_db_error_message); textView.setVisibility(View.VISIBLE); } return view; }
Example #13
Source File: GsonExample.java From auto-matter with Apache License 2.0 | 6 votes |
public static void main(final String... args) throws IOException { // Register the AutoMatterTypeAdapterFactory to handle deserialization Gson gson = new GsonBuilder() .registerTypeAdapterFactory(new AutoMatterTypeAdapterFactory()) .create(); Foobar foobar = new FoobarBuilder() .bar(17) .foo("hello world") .build(); String json = gson.toJson(foobar); out.println("json: " + json); Foobar parsed = gson.fromJson(json, Foobar.class); out.println("parsed: " + parsed); out.println("equals: " + foobar.equals(parsed)); }
Example #14
Source File: VideosRepository.java From tv-samples with Apache License 2.0 | 6 votes |
private void initializeDb(AppDatabase db, String url) throws IOException { // json data String json; if (AppConfiguration.IS_DEBUGGING_VERSION) { // when use debugging version, we won't fetch data from network but using local // json file (only contain 4 video entities in 2 categories.) json = Utils.inputStreamToString(SampleApplication .getInstance() .getApplicationContext() .getResources() .openRawResource(R.raw.live_movie_debug)); Gson gson = new Gson(); VideosWithGoogleTag videosWithGoogleTag = gson.fromJson(json, VideosWithGoogleTag.class); populateDatabase(videosWithGoogleTag,db); } else { buildDatabase(db, url); } }
Example #15
Source File: TestModule.java From syncapp with Apache License 2.0 | 6 votes |
@Provides @Singleton public ApiService apiService() { OkHttpClient client = new OkHttpClient(); final GsonBuilder builder = new GsonBuilder() .registerTypeAdapter(Notification.class, new NotificationAdapter()); final Gson gson = builder.create(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(mockWebServer.url("/")) .addConverterFactory(GsonConverterFactory.create(gson)) .client(client) .build(); ApiService service = retrofit.create(ApiService.class); return service; }
Example #16
Source File: JsonUtils.java From mogu_blog_v2 with Apache License 2.0 | 6 votes |
/** * 将Json转换成Map<String, ?> * * @param json * @param clazz * @return */ public static Map<String, ?> jsonToMap(String json, Class<?> clazz) { Gson gson = new GsonBuilder() .excludeFieldsWithModifiers(Modifier.FINAL, Modifier.TRANSIENT, Modifier.STATIC) .setDateFormat("yyyy-MM-dd HH:mm:ss") .serializeNulls() .create(); Map<String, ?> map = null; try { Type type = new TypeToken<Map<String, ?>>() { }.getType(); map = gson.fromJson(json, type); } catch (JsonSyntaxException e) { e.printStackTrace(); } return map; }
Example #17
Source File: TaxReceiptMobileController.java From nfscan with MIT License | 6 votes |
/** * Generates a signature and a transaction Id that must be processed and used on all other requests to fend off requests that aren't coming from our app * * @return a JSON containing the ResultProcessAuthResponse properties * @see ResultProcessAuthResponse */ @RequestMapping(value = "/fe/taxreceipts/process/auth", method = RequestMethod.POST) public ResponseEntity<String> auth() { HttpHeaders responseHeaders = super.createBasicHttpHeaderResponse(APPLICATION_JSON); Gson gson = new Gson(); ResultResponse resultResponse; try { String signature = signatureUtils.generateSignature(); Date currDate = new Date(); OCRTransaction ocrTransaction = new OCRTransaction(signature, currDate, new SimpleDateFormat(Constants.DATE_FORMAT).format(currDate)); ocrTransactionDAO.save(ocrTransaction); resultResponse = new ResultProcessAuthResponse(true, ocrTransaction.getId(), ocrTransaction.getSignature()); } catch (Exception ex) { ex.printStackTrace(); resultResponse = new ResultResponse(false); } return new ResponseEntity<>(gson.toJson(resultResponse), responseHeaders, HttpStatus.OK); }
Example #18
Source File: Recents.java From QuickLyric with GNU General Public License v3.0 | 6 votes |
public synchronized static Recents getInstance(Context context) { if (instance == null) { Recents.context = context.getApplicationContext(); SharedPreferences prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE); Gson gson = new GsonBuilder().create(); String str = prefs.getString(PREFS_NAME, ""); if (str.equals("")) { instance = new Recents(); } else { try { instance = gson.fromJson(str, Recents.class); } catch (JsonSyntaxException e) { instance = new Recents(); } } } return instance; }
Example #19
Source File: FieldNamingTest.java From gson with Apache License 2.0 | 5 votes |
public void testLowerCaseWithDashes() { Gson gson = getGsonWithNamingPolicy(LOWER_CASE_WITH_DASHES); assertEquals("{'lower-camel':1,'upper-camel':2,'_lower-camel-leading-underscore':3," + "'_-upper-camel-leading-underscore':4,'lower_words':5,'u-p-p-e-r_-w-o-r-d-s':6," + "'annotatedName':7,'lower-id':8,'_9':9}", gson.toJson(new TestNames()).replace('\"', '\'')); }
Example #20
Source File: LocationSerializer.java From PerWorldInventory with GNU General Public License v3.0 | 5 votes |
/** * Serialize a Location into a JsonObject. * * @param location The {@link org.bukkit.Location} * @return The JsonObject in String form */ public static String serialize(Location location) { Gson gson = new Gson(); JsonObject root = new JsonObject(); root.addProperty("world", location.getWorld().getName()); root.addProperty("x", location.getX()); root.addProperty("y", location.getY()); root.addProperty("z", location.getZ()); root.addProperty("pitch", location.getPitch()); root.addProperty("yaw", location.getYaw()); return gson.toJson(root); }
Example #21
Source File: ScriptExecutorThread.java From testgrid with Apache License 2.0 | 5 votes |
/** * Start running thread to read result which sent from the tinkerer. */ @Override public void run() { Gson gson = new Gson(); ChunkedInput<String> input = this.response.readEntity(new ChunkObject()); String chunk; OperationSegment operationSegment = new OperationSegment(); long initTime = Calendar.getInstance().getTimeInMillis(); long currentTime; while ((chunk = input.read()) != null) { synchronized (this) { currentTime = Calendar.getInstance().getTimeInMillis(); if (initTime + MAX_BUFFER_IDLE_TIME_MS < currentTime) { logger.warn("Execution time out for operation " + this.operationId); break; } operationSegment = gson.fromJson(chunk, OperationSegment.class); writeDataToFile(operationSegment, this.segmentCount + 1); this.segmentCount++; } } synchronized (this) { this.isCompleted = true; this.exitValue = operationSegment.getExitValue(); logger.info("Streaming success with exit value " + operationSegment.getExitValue() + " for operation " + this.operationId); } }
Example #22
Source File: PowerRestController.java From sctalk with Apache License 2.0 | 5 votes |
@RequestMapping(value="/power/modify", method= RequestMethod.POST) public void modifyPower(HttpServletRequest request, HttpServletResponse response){ String strData=HttpUtils.getJsonBody(request); Gson gson = new Gson(); power_info power=gson.fromJson(strData,power_info.class); // Create a blocking stub with the channel PowerServiceGrpc.PowerServiceBlockingStub stub = PowerServiceGrpc.newBlockingStub(channel); // Create a request PowerRequest modifyRequest = PowerRequest.newBuilder() .setPowerId(power.getPowerId()) .setPowerUrl(power.getPowerUrl()) .setPowerName(power.getPowerName()) .setParentId(power.getParentId()) .build(); // Send the request using the stub System.out.println("Client sending request"); PowerResponse modifyResponse = stub.modifyPower(modifyRequest); if(modifyResponse.getStatusId()==0){ HttpUtils.setJsonBody(response,new ResponseInfo(0,"修改成功!")); }else { HttpUtils.setJsonBody(response,new ResponseInfo(1,"修改失败!")); } }
Example #23
Source File: HaprampTags.java From 1Rramp-Android with MIT License | 5 votes |
public static ArrayList<String> getUserSelectedTags() { ArrayList<String> tags = new ArrayList<>(); String json = HaprampPreferenceManager.getInstance().getUserSelectedCommunityAsJson(); CommunityListWrapper wr = new Gson().fromJson(json, CommunityListWrapper.class); for (CommunityModel com : wr.getCommunityModels()) { tags.add(com.getmTag()); } return tags; }
Example #24
Source File: TransactionHistoryFragment.java From guarda-android-wallets with GNU General Public License v3.0 | 5 votes |
private void loadFromCache() { String jsonFromPref = sharedManager.getTxsCache(); if (!jsonFromPref.equalsIgnoreCase("")) { Gson gson = new Gson(); Type listType = new TypeToken<Map<String, ArrayList<TransactionItem>>>(){}.getType(); Map<String, ArrayList<TransactionItem>> addrTxsMap = gson.fromJson(jsonFromPref, listType); ArrayList<TransactionItem> txList = addrTxsMap.get(walletManager.getWalletFriendlyAddress()); if (txList != null) { transactionsManager.setTransactionsList(txList); initTransactionHistoryRecycler(); } } }
Example #25
Source File: TbLog.java From BigDataPlatform with GNU General Public License v3.0 | 5 votes |
/** * 设置请求参数 * @param paramMap */ public void setMapToParams(Map<String, String[]> paramMap) { if (paramMap == null) { return; } Map<String, Object> params = new HashMap<>(); for (Map.Entry<String, String[]> param : paramMap.entrySet()) { String key = param.getKey(); String paramValue = (param.getValue() != null && param.getValue().length > 0 ? param.getValue()[0] : ""); String obj = StringUtils.endsWithIgnoreCase(param.getKey(), "password") ? "你是看不见我的" : paramValue; params.put(key,obj); } this.requestParam = new Gson().toJson(params); }
Example #26
Source File: BusActivity.java From KUAS-AP-Material with MIT License | 5 votes |
private void restoreArgs(Bundle savedInstanceState) { if (savedInstanceState != null) { mDate = savedInstanceState.getString("mDate"); mIndex = savedInstanceState.getInt("mIndex"); mInitListPos = savedInstanceState.getInt("mInitListPos"); mInitListOffset = savedInstanceState.getInt("mInitListOffset"); isRetry = savedInstanceState.getBoolean("isRetry"); if (savedInstanceState.containsKey("mJianGongList")) { mJianGongList = new Gson().fromJson(savedInstanceState.getString("mJianGongList"), new TypeToken<List<BusModel>>() { }.getType()); } if (savedInstanceState.containsKey("mYanChaoList")) { mYanChaoList = new Gson().fromJson(savedInstanceState.getString("mYanChaoList"), new TypeToken<List<BusModel>>() { }.getType()); } } else { showDatePickerDialog(); } if (mJianGongList == null) { mJianGongList = new ArrayList<>(); } if (mYanChaoList == null) { mYanChaoList = new ArrayList<>(); } }
Example #27
Source File: DataConverterImpl.java From yandex-translate-api with MIT License | 5 votes |
private static Gson createConverter() { final GsonBuilder builder = new GsonBuilder(); final ServiceLoader<TypeAdapterFactory> serviceLoader = ServiceLoader.load(TypeAdapterFactory.class); serviceLoader.forEach(builder::registerTypeAdapterFactory); return builder.create(); }
Example #28
Source File: HttpUtils.java From CloudReader with Apache License 2.0 | 5 votes |
private Gson getGson() { if (gson == null) { GsonBuilder builder = new GsonBuilder(); builder.setLenient(); builder.setFieldNamingStrategy(new AnnotateNaming()); builder.serializeNulls(); gson = builder.create(); } return gson; }
Example #29
Source File: GetArtifactStoreViewExecutorTest.java From docker-registry-artifact-plugin with Apache License 2.0 | 5 votes |
@Test public void shouldRenderTheTemplateInJSON() throws Exception { GoPluginApiResponse response = new GetArtifactStoreViewExecutor().execute(); Map<String, String> responseHash = new Gson().fromJson(response.responseBody(), new TypeToken<Map<String,String>>(){}.getType()); assertThat(response.responseCode()).isEqualTo(200); assertThat(responseHash).containsEntry("template", Util.readResource("/artifact-store.template.html")); }
Example #30
Source File: NBTToJsonConverter.java From PneumaticCraft with GNU General Public License v3.0 | 5 votes |
public String convert(){ JsonObject json = getObject(tag); String jsonString = json.toString(); JsonParser parser = new JsonParser(); Gson gson = new GsonBuilder().setPrettyPrinting().create(); JsonElement el = parser.parse(jsonString); return gson.toJson(el); // done }