List of usage examples for com.google.gson JsonObject toString
@Override
public String toString()
From source file:com.arangodb.entity.EntityFactory.java
License:Apache License
public static <T> String toJsonString(T obj, boolean includeNullValue) { if (obj != null && obj.getClass().equals(BaseDocument.class)) { String tmp = includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj); JsonParser jsonParser = new JsonParser(); JsonElement jsonElement = jsonParser.parse(tmp); JsonObject jsonObject = jsonElement.getAsJsonObject(); JsonObject result = jsonObject.getAsJsonObject("properties"); JsonElement keyObject = jsonObject.get("_key"); if (keyObject != null && keyObject.getClass() != JsonNull.class) { result.add("_key", jsonObject.get("_key")); }//from w w w.j a va 2 s. com JsonElement handleObject = jsonObject.get("_id"); if (handleObject != null && handleObject.getClass() != JsonNull.class) { result.add("_id", jsonObject.get("_id")); } // JsonElement revisionValue = jsonObject.get("documentRevision"); // result.add("_rev", revisionValue); return result.toString(); } return includeNullValue ? gsonNull.toJson(obj) : gson.toJson(obj); }
From source file:com.att.pirates.controller.ProjectController.java
@RequestMapping(value = "/projects/{prismId}/applicationlist", method = RequestMethod.GET) public @ResponseBody String getApplicationListForPrismId(@PathVariable("prismId") String prismId) { List<ProjectApplications> apps = DataService.getProjectApplications(prismId); JsonObject jsonResponse = new JsonObject(); for (ProjectApplications ap : apps) { jsonResponse.addProperty(ap.getApplicationName(), ap.getApplicationName()); }/*w w w . j a v a 2 s . c o m*/ logger.error(msgHeader + jsonResponse.toString()); return jsonResponse.toString(); }
From source file:com.att.pirates.controller.ProjectController.java
@RequestMapping(value = "/pid/{prismId}/getProjectNotesJson", method = RequestMethod.GET) public @ResponseBody String getCompanies(@PathVariable("prismId") String prismId, HttpServletRequest request) { // logger.error(msgHeader + " getCompanies prismId: " + prismId); JQueryDataTableParamModel param = DataTablesParamUtility.getParam(request); String sEcho = param.sEcho;// w ww. ja v a2 s . c o m int iTotalRecords; // total number of records (unfiltered) int iTotalDisplayRecords; //value will be set when code filters companies by keyword List<Company> allNotes = GlobalDataController.GetCompanies(prismId); iTotalRecords = allNotes.size(); List<Company> companies = new LinkedList<Company>(); for (Company c : allNotes) { if (c.getName().toLowerCase().contains(param.sSearch.toLowerCase()) || c.getAddress().toLowerCase().contains(param.sSearch.toLowerCase()) || c.getTown().toLowerCase().contains(param.sSearch.toLowerCase()) || c.getDateCreated().toLowerCase().contains(param.sSearch.toLowerCase())) { companies.add(c); // add company that matches given search criterion } } iTotalDisplayRecords = companies.size();// number of companies that match search criterion should be returned final int sortColumnIndex = param.iSortColumnIndex; final int sortDirection = param.sSortDirection.equals("asc") ? -1 : 1; Collections.sort(companies, new Comparator<Company>() { @Override public int compare(Company c1, Company c2) { switch (sortColumnIndex) { case 0: return 0; // sort by id is not allowed case 1: return c1.getName().compareTo(c2.getName()) * sortDirection; case 2: return c1.getAddress().compareTo(c2.getAddress()) * sortDirection; case 3: return c1.getTown().compareTo(c2.getTown()) * sortDirection; case 4: SimpleDateFormat yFormat = new SimpleDateFormat("MM/dd/yyyy"); try { Date c1d = yFormat.parse(c1.getDateCreated()); Date c2d = yFormat.parse(c2.getDateCreated()); return c1d.compareTo(c2d) * sortDirection; } catch (ParseException ex) { logger.error(ex.getMessage()); } } return 0; } }); if (companies.size() < param.iDisplayStart + param.iDisplayLength) { companies = companies.subList(param.iDisplayStart, companies.size()); } else { companies = companies.subList(param.iDisplayStart, param.iDisplayStart + param.iDisplayLength); } try { JsonObject jsonResponse = new JsonObject(); jsonResponse.addProperty("sEcho", sEcho); jsonResponse.addProperty("iTotalRecords", iTotalRecords); jsonResponse.addProperty("iTotalDisplayRecords", iTotalDisplayRecords); Gson gson = new Gson(); jsonResponse.add("aaData", gson.toJsonTree(companies)); String tmp = jsonResponse.toString(); // logger.error(msgHeader + ".. json string: " + tmp); return jsonResponse.toString(); } catch (JsonIOException e) { logger.error(msgHeader + e.getMessage()); } return null; }
From source file:com.azure.webapi.LoginManager.java
License:Open Source License
/** * Creates a User based on a Windows Azure Mobile Service JSON object * containing a UserId and Authentication Token * //from w w w .j av a 2s . c o m * @param json * JSON object used to create the User * @return The created user if it is a valid JSON object. Null otherwise * @throws MobileServiceException */ private MobileServiceUser createUserFromJSON(JsonObject json) throws MobileServiceException { if (json == null) { throw new IllegalArgumentException("json can not be null"); } // If the JSON object is valid, create a MobileServiceUser object if (json.has(USER_JSON_PROPERTY)) { JsonObject jsonUser = json.getAsJsonObject(USER_JSON_PROPERTY); if (!jsonUser.has(USERID_JSON_PROPERTY)) { throw new JsonParseException(USERID_JSON_PROPERTY + " property expected"); } String userId = jsonUser.get(USERID_JSON_PROPERTY).getAsString(); MobileServiceUser user = new MobileServiceUser(userId); if (!json.has(TOKEN_JSON_PARAMETER)) { throw new JsonParseException(TOKEN_JSON_PARAMETER + " property expected"); } user.setAuthenticationToken(json.get(TOKEN_JSON_PARAMETER).getAsString()); return user; } else { // If the JSON contains an error property show it, otherwise raise // an error with JSON content if (json.has("error")) { throw new MobileServiceException(json.get("error").getAsString()); } else { throw new JsonParseException(json.toString()); } } }
From source file:com.azure.webapi.MobileServiceJsonTable.java
License:Open Source License
/** * Inserts a JsonObject into a Mobile Service Table * /* w w w. j av a2s .c o m*/ * @param element * The JsonObject to insert * @param parameters * A list of user-defined parameters and values to include in the request URI query string * @param callback * Callback to invoke when the operation is completed * @throws InvalidParameterException */ public void insert(final JsonObject element, List<Pair<String, String>> parameters, final TableJsonOperationCallback callback) { try { removeIdFromJson(element); } catch (InvalidParameterException e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } String content = element.toString(); ServiceFilterRequest post; try { Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon(); uriBuilder.path(TABLES_URL); uriBuilder.appendPath(URLEncoder.encode(mTableName, MobileServiceClient.UTF8_ENCODING)); if (parameters != null && parameters.size() > 0) { for (Pair<String, String> parameter : parameters) { uriBuilder.appendQueryParameter(parameter.first, parameter.second); } } post = new ServiceFilterRequestImpl(new HttpPost(uriBuilder.build().toString())); post.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE); } catch (UnsupportedEncodingException e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } try { post.setContent(content); } catch (Exception e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } executeTableOperation(post, new TableJsonOperationCallback() { @Override public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) { if (callback != null) { if (exception == null && jsonEntity != null) { JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, jsonEntity); callback.onCompleted(patchedJson, exception, response); } else { callback.onCompleted(jsonEntity, exception, response); } } } }); }
From source file:com.azure.webapi.MobileServiceJsonTable.java
License:Open Source License
/** * Updates an element from a Mobile Service Table * /*ww w.ja v a 2s. com*/ * @param element * The JsonObject to update * @param parameters * A list of user-defined parameters and values to include in the request URI query string * @param callback * Callback to invoke when the operation is completed */ public void update(final JsonObject element, final List<Pair<String, String>> parameters, final TableJsonOperationCallback callback) { try { updateIdProperty(element); if (!element.has("id") || element.get("id").getAsInt() == 0) { throw new IllegalArgumentException( "You must specify an id property with a valid value for updating an object."); } } catch (Exception e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } String content = element.toString(); ServiceFilterRequest putRequest; try { Uri.Builder uriBuilder = Uri.parse(mClient.getAppUrl().toString()).buildUpon(); uriBuilder.path(TABLES_URL); //This needs to reference to "api/" uriBuilder.appendPath(URLEncoder.encode(mTableName, MobileServiceClient.UTF8_ENCODING)); uriBuilder.appendPath(Integer.valueOf(getObjectId(element)).toString()); if (parameters != null && parameters.size() > 0) { for (Pair<String, String> parameter : parameters) { uriBuilder.appendQueryParameter(parameter.first, parameter.second); } } putRequest = new ServiceFilterRequestImpl(new HttpPut(uriBuilder.build().toString())); putRequest.addHeader(HTTP.CONTENT_TYPE, MobileServiceConnection.JSON_CONTENTTYPE); } catch (UnsupportedEncodingException e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } try { putRequest.setContent(content); } catch (Exception e) { if (callback != null) { callback.onCompleted(null, e, null); } return; } executeTableOperation(putRequest, new TableJsonOperationCallback() { // TODO webapi is different in response. It return status code only @Override public void onCompleted(JsonObject jsonEntity, Exception exception, ServiceFilterResponse response) { if (callback != null) { if (exception == null && jsonEntity != null) { JsonObject patchedJson = patchOriginalEntityWithResponseEntity(element, jsonEntity); callback.onCompleted(patchedJson, exception, response); } else { callback.onCompleted(jsonEntity, exception, response); } } } }); }
From source file:com.azure.webapi.MobileServiceTableBase.java
License:Open Source License
/** * Patches the original entity with the one returned in the response after * executing the operation//from w w w . j a v a2 s . co m * * @param originalEntity * The original entity * @param newEntity * The entity obtained after executing the operation * @return */ protected JsonObject patchOriginalEntityWithResponseEntity(JsonObject originalEntity, JsonObject newEntity) { // Patch the object to return with the new values JsonObject patchedEntityJson = (JsonObject) new JsonParser().parse(originalEntity.toString()); for (Map.Entry<String, JsonElement> entry : newEntity.entrySet()) { patchedEntityJson.add(entry.getKey(), entry.getValue()); } return patchedEntityJson; }
From source file:com.baidu.mywork.util.RemoteHttpUtil.java
License:Apache License
/** * ???json?post?// w ww . j a v a 2 s . c om * * @throws IOException * @throws * */ public static String fetchJsonHttpResponse(String contentUrl, Map<String, String> headerMap, JsonObject bodyJson) throws IOException { Executor executor = Executor.newInstance(httpClient); Request request = Request.Post(contentUrl); if (headerMap != null && !headerMap.isEmpty()) { for (Map.Entry<String, String> m : headerMap.entrySet()) { request.addHeader(m.getKey(), m.getValue()); } } if (bodyJson != null) { request.bodyString(bodyJson.toString(), ContentType.APPLICATION_JSON); } return executor.execute(request).returnContent().asString(); }
From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.java
License:Open Source License
/** * ??//w ww . j ava 2 s. c om * * @param date * ? day ??00:00 23:59 * @param keywords * ?? ?????? * @return */ public HashMap<String, Object> billRecords(String date, String keywords) { HashMap<String, Object> validate = accountValidate(); if (validate != null) return validate; if ((isEmpty(date))) { logger.debug("?: "); throw new IllegalArgumentException("?: "); } CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = null; try { httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https"); } catch (Exception e1) { //e1.printStackTrace(); logger.error(e1.getMessage()); throw new RuntimeException("?httpclient" + e1.getMessage()); } String result = ""; try { HttpPost httppost = (HttpPost) getHttpRequestBase(1, BillRecords); String requsetbody = ""; if (BODY_TYPE == BodyType.Type_JSON) { JsonObject json = new JsonObject(); json.addProperty("appId", App_ID); json.addProperty("date", date); if (!(isEmpty(keywords))) json.addProperty("keywords", keywords); requsetbody = json.toString(); } else { StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><BillRecords>"); sb.append("<appId>").append(App_ID).append("</appId>").append("<date>").append(date) .append("</date>"); if (!(isEmpty(keywords))) sb.append("<keywords>").append(keywords).append("</keywords>"); sb.append("</BillRecords>").toString(); requsetbody = sb.toString(); } logger.info("billRecords Request body = : " + requsetbody); //? System.out.println("" + requsetbody); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8"))); requestBody.setContentLength(requsetbody.getBytes("UTF-8").length); httppost.setEntity(requestBody); HttpResponse response = httpclient.execute(httppost); status = response.getStatusLine().getStatusCode(); System.out.println("Https??" + status); HttpEntity entity = response.getEntity(); if (entity != null) result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); return getMyError("172001", ""); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); return getMyError("172002", ""); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } logger.info("billRecords response body = " + result); try { if (BODY_TYPE == BodyType.Type_JSON) { return jsonToMap(result); } else { return xmlToMap(result); } } catch (Exception e) { return getMyError("172003", ""); } }
From source file:com.baomidou.springwind.util.yuntongxin.CCPRestSDK.java
License:Open Source License
/** * ???//from w w w. j a va 2s . c om * * @param verifyCode * ? ?????4-8? * @param to * ? ?? * @param displayNum * ?? ?????? * @param playTimes * ?? 1?31 * @param respUrl * ?? ??????Url???? * @param lang * ?? * @param userData * ?? ?? * @param welcomePrompt * ?? wav??????????verifyCodeplayVerifyCode * @param playVerifyCode * ?? wav????????verifyCode???playVerifyCode * @param maxCallTime * ?? ? * @return */ public HashMap<String, Object> voiceVerify(String verifyCode, String to, String displayNum, String playTimes, String respUrl, String lang, String userData, String welcomePrompt, String playVerifyCode, String maxCallTime) { HashMap<String, Object> validate = accountValidate(); if (validate != null) return validate; if ((isEmpty(verifyCode)) || (isEmpty(to))) throw new IllegalArgumentException("?:" + (isEmpty(verifyCode) ? " ?? " : "") + (isEmpty(to) ? " ?? " : "") + ""); CcopHttpClient chc = new CcopHttpClient(); DefaultHttpClient httpclient = null; try { httpclient = chc.registerSSL(SERVER_IP, "TLS", Integer.parseInt(SERVER_PORT), "https"); } catch (Exception e1) { e1.printStackTrace(); throw new RuntimeException("?httpclient" + e1.getMessage()); } String result = ""; try { HttpPost httppost = (HttpPost) getHttpRequestBase(1, VoiceVerify); String requsetbody = ""; if (BODY_TYPE == BodyType.Type_JSON) { JsonObject json = new JsonObject(); json.addProperty("appId", App_ID); json.addProperty("verifyCode", verifyCode); json.addProperty("to", to); if (!(isEmpty(displayNum))) json.addProperty("displayNum", displayNum); if (!(isEmpty(playTimes))) json.addProperty("playTimes", playTimes); if (!(isEmpty(respUrl))) json.addProperty("respUrl", respUrl); if (!(isEmpty(lang))) json.addProperty("lang", lang); if (!(isEmpty(userData))) json.addProperty("userData", userData); if (!(isEmpty(welcomePrompt))) json.addProperty("welcomePrompt", welcomePrompt); if (!(isEmpty(playVerifyCode))) json.addProperty("playVerifyCode", playVerifyCode); if (!(isEmpty(maxCallTime))) json.addProperty("maxCallTime", maxCallTime); requsetbody = json.toString(); } else { StringBuilder sb = new StringBuilder("<?xml version='1.0' encoding='utf-8'?><VoiceVerify>"); sb.append("<appId>").append(App_ID).append("</appId>").append("<verifyCode>").append(verifyCode) .append("</verifyCode>").append("<to>").append(to).append("</to>"); if (!(isEmpty(displayNum))) sb.append("<displayNum>").append(displayNum).append("</displayNum>"); if (!(isEmpty(playTimes))) sb.append("<playTimes>").append(playTimes).append("</playTimes>"); if (!(isEmpty(respUrl))) sb.append("<respUrl>").append(respUrl).append("</respUrl>"); if (!(isEmpty(lang))) sb.append("<lang>").append(lang).append("</lang>"); if (!(isEmpty(userData))) sb.append("<userData>").append(userData).append("</userData>"); if (!(isEmpty(welcomePrompt))) sb.append("<welcomePrompt>").append(welcomePrompt).append("</welcomePrompt>"); if (!(isEmpty(playVerifyCode))) sb.append("<playVerifyCode>").append(playVerifyCode).append("</playVerifyCode>"); if (!(isEmpty(maxCallTime))) sb.append("<maxCallTime>").append(maxCallTime).append("</maxCallTime>"); sb.append("</VoiceVerify>").toString(); requsetbody = sb.toString(); } logger.info("voiceVerify Request body = : " + requsetbody); System.out.println("" + requsetbody); BasicHttpEntity requestBody = new BasicHttpEntity(); requestBody.setContent(new ByteArrayInputStream(requsetbody.getBytes("UTF-8"))); requestBody.setContentLength(requsetbody.getBytes("UTF-8").length); httppost.setEntity(requestBody); HttpResponse response = httpclient.execute(httppost); status = response.getStatusLine().getStatusCode(); System.out.println("Https??" + status); HttpEntity entity = response.getEntity(); if (entity != null) result = EntityUtils.toString(entity, "UTF-8"); EntityUtils.consume(entity); } catch (IOException e) { e.printStackTrace(); logger.error(e.getMessage()); return getMyError("172001", ""); } catch (Exception e) { e.printStackTrace(); logger.error(e.getMessage()); return getMyError("172002", ""); } finally { if (httpclient != null) httpclient.getConnectionManager().shutdown(); } logger.info("voiceVerify response body = " + result); try { if (BODY_TYPE == BodyType.Type_JSON) { return jsonToMap(result); } else { return xmlToMap(result); } } catch (Exception e) { return getMyError("172003", ""); } }