List of usage examples for com.google.gson JsonObject get
public JsonElement get(String memberName)
From source file:com.avapira.bobroreader.hanabira.entity.HanabiraEntity.java
License:Open Source License
private static HanabiraPost createAndSavePost(JsonObject postObject, int threadId, String boardKey) { // todo files int postId = postObject.get("post_id").getAsInt(); LocalDateTime modifiedDate = extractLocatDateTime(postObject.get("last_modified")); HanabiraPost cachedPost = Hanabira.getStem().findPostById(postId); if (cachedPost != null) { if (modifiedDate == null || !cachedPost.isUpToDate(modifiedDate)) { // update cachedPost.setModifiedDate(modifiedDate); cachedPost.setMessage(postObject.get("message").getAsString()); cachedPost.setName(postObject.get("name").getAsString()); cachedPost.setSubject(postObject.get("subject").getAsString()); }//ww w.j av a 2 s .c o m } else { // brand new post int displayId = postObject.get("display_id").getAsInt(); LocalDateTime createdDate = extractLocatDateTime(postObject.get("date")); String message = postObject.get("message").getAsString(); String subject = postObject.get("subject").getAsString(); String name = postObject.get("name").getAsString(); boolean op = postObject.get("op").getAsBoolean(); int boardId = boardKey != null ? HanabiraBoard.Info.getIdForKey(boardKey) : postObject.get("board_id").getAsInt(); cachedPost = new HanabiraPost(displayId, modifiedDate, createdDate, postId, message, subject, boardId, name, threadId, op); Hanabira.getStem().savePost(cachedPost, boardKey); } return cachedPost; }
From source file:com.axj.apiw.util.JSONUtils.java
License:Apache License
/** * JsonObject??itemName/*from w w w.j a v a 2s . c o m*/ */ public static String getString(JsonObject jobj, String itemName) { if (jobj == null) return null; JsonElement le = jobj.get(itemName); if (le == null) return null; String val = le.getAsString(); return val; }
From source file:com.azure.webapi.JsonEntityParser.java
License:Open Source License
/** * Changes returned JSon object's id property name to match with type's id property name. * @param element/* w ww . j av a 2s .c o m*/ * @param propertyName */ private static void changeIdPropertyName(JsonObject element, String propertyName) { // If the property name is id or if there's no id defined, then return without performing changes if (propertyName.equals("id") || propertyName.length() == 0) return; // Get the current id value and remove the JSon property JsonElement idElement = element.get("id"); if (idElement != null) { String value = idElement.getAsString(); element.remove("id"); // Create a new id property using the given property name element.addProperty(propertyName, value); } }
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 a2s. 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
/** * Removes the Id property from a JsonObject * /*from w ww. ja v a 2 s.c o m*/ * @param json * The JsonObject to modify */ private void removeIdFromJson(final JsonObject json) { // Remove id property if exists String[] idPropertyNames = new String[] { "id", "Id", "iD", "ID" }; for (int i = 0; i < 4; i++) { String idProperty = idPropertyNames[i]; if (json.has(idProperty)) { JsonElement idElement = json.get(idProperty); if (isValidTypeId(idElement) && idElement.getAsInt() != 0) { throw new InvalidParameterException( "The entity to insert should not have " + idProperty + " property defined"); } json.remove(idProperty); } } }
From source file:com.azure.webapi.MobileServiceJsonTable.java
License:Open Source License
/** * Updates an element from a Mobile Service Table * /*from ww w .ja va2 s. co m*/ * @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.MobileServiceJsonTable.java
License:Open Source License
/** * Retrieves a set of rows from using the specified URL * /*from ww w .ja v a2 s . c om*/ * @param query * The URL used to retrieve the rows * @param callback * Callback to invoke when the operation is completed */ private void executeGetRecords(final String url, final TableJsonQueryCallback callback) { ServiceFilterRequest request = new ServiceFilterRequestImpl(new HttpGet(url)); MobileServiceConnection conn = mClient.createConnection(); // Create AsyncTask to execute the request and parse the results new RequestAsyncTask(request, conn) { @Override protected void onPostExecute(ServiceFilterResponse response) { if (callback != null) { if (mTaskException == null && response != null) { JsonElement results = null; int count = 0; try { // Parse the results using the given Entity class String content = response.getContent(); JsonElement json = new JsonParser().parse(content); if (json.isJsonObject()) { JsonObject jsonObject = json.getAsJsonObject(); // If the response has count property, store its // value if (jsonObject.has("results") && jsonObject.has("count")) { // inlinecount // result count = jsonObject.get("count").getAsInt(); results = jsonObject.get("results"); } else { results = json; } } else { results = json; } } catch (Exception e) { callback.onCompleted(null, 0, new MobileServiceException("Error while retrieving data from response.", e), response); return; } callback.onCompleted(results, count, null, response); } else { callback.onCompleted(null, 0, mTaskException, response); } } } }.execute(); }
From source file:com.azure.webapi.MobileServiceTableBase.java
License:Open Source License
/** * Gets the id property from a given element * /*from w w w .j av a 2 s.c om*/ * @param element * The element to use * @return The id of the element */ protected int getObjectId(Object element) { if (element == null) { throw new InvalidParameterException("Element cannot be null"); } else if (element instanceof Integer) { return ((Integer) element).intValue(); } JsonObject jsonObject; if (element instanceof JsonObject) { jsonObject = (JsonObject) element; } else { jsonObject = mClient.getGsonBuilder().create().toJsonTree(element).getAsJsonObject(); } updateIdProperty(jsonObject); JsonElement idProperty = jsonObject.get("id"); if (idProperty instanceof JsonNull || idProperty == null) { throw new InvalidParameterException("Element must contain id property"); } return idProperty.getAsInt(); }
From source file:com.b12kab.tmdblibrary.AccountStateDeserializer.java
License:Apache License
@Override public AccountState deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { AccountState accountState = new AccountState(); String convertVariable = ""; JsonObject obj = (JsonObject) json; JsonElement element;//from ww w .j a v a 2s . c o m JsonElement ratingElement; JsonPrimitive rating; try { convertVariable = "id"; element = obj.get("id"); if (element != null) { if (element.isJsonPrimitive()) { if (element.getAsJsonPrimitive().isNumber()) { accountState.setId(element.getAsInt()); } } } convertVariable = "favorite"; element = obj.get("favorite"); if (element != null) { if (element.isJsonPrimitive()) { if (element.getAsJsonPrimitive().isBoolean()) { accountState.setFavorite(element.getAsBoolean()); } } } accountState.setRated(null); convertVariable = "rated"; element = obj.get("rated"); if (element != null) { if (element.isJsonObject()) { if (element.getAsJsonObject().has("value")) { ratingElement = element.getAsJsonObject().get("value"); if (ratingElement.isJsonPrimitive()) { // rating if (ratingElement.getAsJsonPrimitive().isNumber()) { accountState.setRated(ratingElement.getAsFloat()); } } } } } convertVariable = "watchlist"; element = obj.get("watchlist"); if (element != null) { if (element.isJsonPrimitive()) { if (element.getAsJsonPrimitive().isBoolean()) { accountState.setWatchlist(element.getAsBoolean()); } } } } catch (NullPointerException npe) { Log.e(TAG, "Processing " + convertVariable + " response from Tmdb, NullPointerException occurred" + npe.toString()); return null; } catch (NumberFormatException npe) { Log.e(TAG, "Processing " + convertVariable + " response from Tmdb, NumberFormatException occurred" + npe.toString()); return null; } catch (IllegalStateException ise) { Log.e(TAG, "Processing " + convertVariable + " response from Tmdb, IllegalStateException occurred" + ise.toString()); } return accountState; }
From source file:com.baidu.cc.configuration.service.impl.VersionServiceImpl.java
License:Apache License
/** * ??./*w w w . ja v a 2 s. c o m*/ * * @param file * * @param versionId * the version id * @throws IOException * ? */ @Override public void importFromFile(File file, Long versionId) throws IOException { byte[] byteArray = FileUtils.readFileToByteArray(file); Hex encoder = new Hex(); try { byteArray = encoder.decode(byteArray); } catch (DecoderException e) { throw new IOException(e.getMessage()); } String json = new String(byteArray, SysUtils.UTF_8); // parse from gson JsonParser jsonParser = new JsonParser(); JsonElement je = jsonParser.parse(json); if (!je.isJsonArray()) { throw new RuntimeException("illegal json string. must be json array."); } JsonArray jsonArray = je.getAsJsonArray(); int size = jsonArray.size(); Version version = new Version(); List<ConfigGroup> groups = new ArrayList<ConfigGroup>(); ConfigGroup group; List<ConfigItem> items; ConfigItem item; for (int i = 0; i < size; i++) { JsonObject jo = jsonArray.get(i).getAsJsonObject(); group = gson.fromJson(jo, ConfigGroup.class); // get sub configuration item JsonArray subItemsJson = jo.get(CONFIG_ITEMS_ELE).getAsJsonArray(); int subSize = subItemsJson.size(); items = new ArrayList<ConfigItem>(); for (int j = 0; j < subSize; j++) { item = gson.fromJson(subItemsJson.get(j), ConfigItem.class); items.add(item); } group.setConfigItems(items); groups.add(group); } version.setConfigGroups(groups); configCopyService.copyConfigItemsFromVersion(version, versionId); }