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: 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 #4
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 #5
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 #6
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 #7
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 #8
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 #9
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 #10
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 #11
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 #12
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 #13
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 #14
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 #15
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 #16
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 #17
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 #18
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 #19
Source File: EoscDataManager.java From EosCommander with MIT License | 5 votes |
public Observable<Action> buyRamInAssetAction(String payer, String receiver, String assetQuantity) { JsonObject object = new JsonObject(); object.addProperty("payer", new TypeAccountName(payer).toString()); object.addProperty("receiver", new TypeAccountName(receiver).toString()); object.addProperty("quant", new TypeAsset( assetQuantity ).toString()); return getActionAfterBindArgs( EOSIO_SYSTEM_ACCOUNT, payer, "buyram", new Gson().toJson(object)); }
Example #20
Source File: TigerGraphSinkTask.java From ecosys with Apache License 2.0 | 5 votes |
public TigerGraphSinkTask () { this.converter = new JsonConverter(); this.conn = null; this.gson = new Gson(); this.accumulated = 0; this.lastCommitTime = System.currentTimeMillis(); this.ret = new StringBuilder(); this.parseTime = 0; }
Example #21
Source File: TestUtils.java From ZhihuDaily with Apache License 2.0 | 5 votes |
public static Repository getRepository() { if (mRepository != null) { return mRepository; } else { String endpointUrl = "http://news.at.zhihu.com/api/4/"; Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create(); GsonConverterFactory gsonConverterFactory = GsonConverterFactory.create(gson); HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .cache(new Cache(FileUtils.getHttpCacheDir(RuntimeEnvironment.application), Constants.Config.HTTP_CACHE_SIZE)) .connectTimeout(Constants.Config.HTTP_CONNECT_TIMEOUT, TimeUnit.MILLISECONDS) .readTimeout(Constants.Config.HTTP_READ_TIMEOUT, TimeUnit.MILLISECONDS) .addInterceptor(new CacheInterceptor()) .build(); OkHttpClient newClient = client.newBuilder().addInterceptor(loggingInterceptor).build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl(endpointUrl) .client(newClient) .addConverterFactory(gsonConverterFactory) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); mRepository=new RepositoryImpl(retrofit); return mRepository; } }
Example #22
Source File: ShiroAuthenticatingFilter.java From springboot-admin with Apache License 2.0 | 5 votes |
@Override protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception { //获取请求token,如果token不存在,直接返回401 String token = getRequestToken((HttpServletRequest) request); if(StringUtils.isBlank(token)){ HttpServletResponse httpResponse = (HttpServletResponse) response; String json = new Gson().toJson(Result.error(HttpStatus.SC_UNAUTHORIZED, "token失效")); httpResponse.getWriter().print(json); return false; } return executeLogin(request, response); }
Example #23
Source File: ManageVPN.java From solace-samples-semp with Apache License 2.0 | 5 votes |
private void handleError(ApiException ae) { Gson gson = new Gson(); String responseString = ae.getResponseBody(); SempMetaOnlyResponse respObj = gson.fromJson(responseString, SempMetaOnlyResponse.class); SempError errorInfo = respObj.getMeta().getError(); System.out.println("Error during operation. Details:" + "\nHTTP Status Code: " + ae.getCode() + "\nSEMP Error Code: " + errorInfo.getCode() + "\nSEMP Error Status: " + errorInfo.getStatus() + "\nSEMP Error Descriptions: " + errorInfo.getDescription()); }
Example #24
Source File: SAML2GrantManager.java From carbon-identity with Apache License 2.0 | 5 votes |
public void getAccessToken(HttpServletRequest request, HttpServletResponse response) throws SSOAgentException { String samlAssertionString = ((LoggedInSessionBean) request.getSession(false). getAttribute(SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO(). getAssertionString(); String clientLogin = ssoAgentConfig.getOAuth2().getClientId() + ":" + ssoAgentConfig.getOAuth2().getClientSecret(); String queryParam = "grant_type=" + SSOAgentConstants.OAuth2.SAML2_BEARER_GRANT_TYPE + "&assertion=" + URLEncoder.encode(Base64.encodeBytes( samlAssertionString.getBytes(Charset.forName("UTF-8"))).replaceAll("\n", "")); String additionalQueryParam = ssoAgentConfig.getRequestQueryParameters(); if (additionalQueryParam != null) { queryParam = queryParam + additionalQueryParam; } String accessTokenResponse = executePost(queryParam, Base64.encodeBytes(clientLogin.getBytes(Charset.forName("UTF-8"))) .replace("\n", "")); Gson gson = new Gson(); LoggedInSessionBean.AccessTokenResponseBean accessTokenResp = gson.fromJson(accessTokenResponse, LoggedInSessionBean.AccessTokenResponseBean.class); ((LoggedInSessionBean) request.getSession(false).getAttribute( SSOAgentConstants.SESSION_BEAN_NAME)).getSAML2SSO() .setAccessTokenResponseBean(accessTokenResp); }
Example #25
Source File: ClaimImpl.java From JWTDecode.Android with MIT License | 5 votes |
@Override public <T> T asObject(Class<T> tClazz) throws DecodeException { try { if (value.isJsonNull()) { return null; } return new Gson().fromJson(value, tClazz); } catch (JsonSyntaxException e) { throw new DecodeException("Failed to decode claim as " + tClazz.getSimpleName(), e); } }
Example #26
Source File: FhirStu3.java From synthea with Apache License 2.0 | 5 votes |
@SuppressWarnings("rawtypes") private static Map loadLanguageLookup() { String filename = "language_lookup.json"; try { String json = Utilities.readResource(filename); Gson g = new Gson(); return g.fromJson(json, HashMap.class); } catch (Exception e) { System.err.println("ERROR: unable to load json: " + filename); e.printStackTrace(); throw new ExceptionInInitializerError(e); } }
Example #27
Source File: BlockExplorerClient.java From trust-wallet-android-source with GNU General Public License v3.0 | 5 votes |
public BlockExplorerClient( OkHttpClient httpClient, Gson gson, EthereumNetworkRepositoryType networkRepository) { this.httpClient = httpClient; this.gson = gson; this.networkRepository = networkRepository; this.networkRepository.addOnChangeDefaultNetwork(this::onNetworkChanged); NetworkInfo networkInfo = networkRepository.getDefaultNetwork(); onNetworkChanged(networkInfo); }
Example #28
Source File: FMPoetryDetailComment.java From PoetryWeather with Apache License 2.0 | 5 votes |
/** * 评论的测试数据 * * @return */ private List<CommentDetailBean> generaTestData() { Gson gson = new Gson(); commentBean = gson.fromJson(testJson, CommentBean.class); List<CommentDetailBean> commentList = commentBean.getData().getList(); return commentList; }
Example #29
Source File: ExpectedSubtypesAdapter.java From immutables with Apache License 2.0 | 5 votes |
private ExpectedSubtypesAdapter(Gson gson, TypeToken<T> type, TypeToken<? extends T>[] subtypes) { if (subtypes.length < 1) { throw new IllegalArgumentException("At least one subtype should be specified"); } if (gson == null) { throw new NullPointerException("supplied Gson is null"); } if (type == null) { throw new NullPointerException("supplied type Gson is null"); } this.gson = gson; this.type = type; this.subtypes = subtypes.clone(); this.adapters = lookupAdapters(); }
Example #30
Source File: TsLintParserImpl.java From SonarTsPlugin with MIT License | 5 votes |
@Override public Map<String, List<TsLintIssue>> parse(List<String> toParse) { GsonBuilder builder = new GsonBuilder(); Gson gson = builder.create(); List<TsLintIssue> allIssues = new ArrayList<>(); for (String batch : toParse) { TsLintIssue[] batchIssues = gson.fromJson(getFixedUpOutput(batch), TsLintIssue[].class); if (batchIssues == null) { continue; } for (TsLintIssue batchIssue : batchIssues) { allIssues.add(batchIssue); } } // Remap by filename Map<String, List<TsLintIssue>> toReturn = new HashMap<>(); for (TsLintIssue issue : allIssues) { List<TsLintIssue> issuesByFile = toReturn.get(issue.getName()); if (issuesByFile == null) { issuesByFile = new ArrayList<>(); toReturn.put(issue.getName(), issuesByFile); } issuesByFile.add(issue); } return toReturn; }