List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:com.flipkart.android.proteus.parser.custom.ViewGroupParser.java
License:Apache License
@Override public boolean handleChildren(ProteusView view) { ProteusViewManager viewManager = view.getViewManager(); LayoutBuilder builder = viewManager.getLayoutBuilder(); JsonObject layout = viewManager.getLayout(); JsonElement children = layout.get(ProteusConstants.CHILDREN); JsonObject data = viewManager.getDataContext().getData(); int dataIndex = viewManager.getDataContext().getIndex(); Styles styles = view.getViewManager().getStyles(); if (null != children && !children.isJsonNull()) { if (children.isJsonArray()) { ProteusView child;// w w w . ja v a 2 s .co m for (JsonElement jsonElement : children.getAsJsonArray()) { child = builder.build((ViewGroup) view, jsonElement.getAsJsonObject(), data, dataIndex, styles); addView(view, child); } } else if (children.isJsonObject()) { handleDataDrivenChildren(builder, view, viewManager, children.getAsJsonObject(), data, styles, dataIndex); } } return true; }
From source file:com.flipkart.android.proteus.toolbox.ColorUtils.java
License:Apache License
private static ColorStateList inflateFromJson(Context context, JsonObject jsonObject) { ColorStateList result = null;// w w w . ja va2 s .com JsonElement type = jsonObject.get("type"); if (null != type && type.isJsonPrimitive()) { String colorType = type.getAsString(); if (TextUtils.equals(colorType, "selector")) { JsonElement childrenElement = jsonObject.get("children"); if (null != childrenElement && childrenElement.isJsonArray()) { JsonArray children = childrenElement.getAsJsonArray(); int listAllocated = 20; int listSize = 0; int[] colorList = new int[listAllocated]; int[][] stateSpecList = new int[listAllocated][]; for (int idx = 0; idx < children.size(); idx++) { JsonElement itemObject = children.get(idx); if (!itemObject.isJsonObject()) { continue; } Set<Map.Entry<String, JsonElement>> entrySet = ((JsonObject) itemObject).entrySet(); if (entrySet.size() == 0) { continue; } int j = 0; Integer baseColor = null; float alphaMod = 1.0f; int[] stateSpec = new int[entrySet.size() - 1]; boolean ignoreItem = false; for (Map.Entry<String, JsonElement> entry : entrySet) { if (ignoreItem) { break; } if (!entry.getValue().isJsonPrimitive()) { continue; } Integer attributeId = getAttribute(entry.getKey()); if (null != attributeId) { switch (attributeId) { case android.R.attr.type: if (!TextUtils.equals("item", entry.getValue().getAsString())) { ignoreItem = true; } break; case android.R.attr.color: String colorRes = entry.getValue().getAsString(); if (!TextUtils.isEmpty(colorRes)) { baseColor = getColorFromAttributeValue(context, colorRes); } break; case android.R.attr.alpha: String alphaStr = entry.getValue().getAsString(); if (!TextUtils.isEmpty(alphaStr)) { alphaMod = Float.parseFloat(alphaStr); } break; default: stateSpec[j++] = entry.getValue().getAsBoolean() ? attributeId : -attributeId; break; } } } if (!ignoreItem) { stateSpec = StateSet.trimStateSet(stateSpec, j); if (null == baseColor) { throw new IllegalStateException("No Color Specified"); } if (listSize + 1 >= listAllocated) { listAllocated = idealIntArraySize(listSize + 1); int[] ncolor = new int[listAllocated]; System.arraycopy(colorList, 0, ncolor, 0, listSize); int[][] nstate = new int[listAllocated][]; System.arraycopy(stateSpecList, 0, nstate, 0, listSize); colorList = ncolor; stateSpecList = nstate; } final int color = modulateColorAlpha(baseColor, alphaMod); colorList[listSize] = color; stateSpecList[listSize] = stateSpec; listSize++; } } if (listSize > 0) { int[] colors = new int[listSize]; int[][] stateSpecs = new int[listSize][]; System.arraycopy(colorList, 0, colors, 0, listSize); System.arraycopy(stateSpecList, 0, stateSpecs, 0, listSize); result = new ColorStateList(stateSpecs, colors); } } } } return result; }
From source file:com.flipkart.android.proteus.toolbox.Utils.java
License:Apache License
public static Result readJson(String path, JsonObject data, int index) { // replace INDEX reference with index value if (ProteusConstants.INDEX.equals(path)) { path = path.replace(ProteusConstants.INDEX, String.valueOf(index)); return Result.success(new JsonPrimitive(path)); } else {//from w w w .j a v a 2 s. c o m StringTokenizer tokenizer = new StringTokenizer(path, ProteusConstants.DATA_PATH_DELIMITERS); JsonElement elementToReturn = data; JsonElement tempElement; JsonArray tempArray; while (tokenizer.hasMoreTokens()) { String segment = tokenizer.nextToken(); if (elementToReturn == null) { return Result.NO_SUCH_DATA_PATH_EXCEPTION; } if (elementToReturn.isJsonNull()) { return Result.JSON_NULL_EXCEPTION; } if ("".equals(segment)) { continue; } if (elementToReturn.isJsonArray()) { tempArray = elementToReturn.getAsJsonArray(); if (ProteusConstants.INDEX.equals(segment)) { if (index < tempArray.size()) { elementToReturn = tempArray.get(index); } else { return Result.NO_SUCH_DATA_PATH_EXCEPTION; } } else if (ProteusConstants.ARRAY_DATA_LENGTH_REFERENCE.equals(segment)) { elementToReturn = new JsonPrimitive(tempArray.size()); } else if (ProteusConstants.ARRAY_DATA_LAST_INDEX_REFERENCE.equals(segment)) { if (tempArray.size() == 0) { return Result.NO_SUCH_DATA_PATH_EXCEPTION; } elementToReturn = tempArray.get(tempArray.size() - 1); } else { try { index = Integer.parseInt(segment); } catch (NumberFormatException e) { return Result.INVALID_DATA_PATH_EXCEPTION; } if (index < tempArray.size()) { elementToReturn = tempArray.get(index); } else { return Result.NO_SUCH_DATA_PATH_EXCEPTION; } } } else if (elementToReturn.isJsonObject()) { tempElement = elementToReturn.getAsJsonObject().get(segment); if (tempElement != null) { elementToReturn = tempElement; } else { return Result.NO_SUCH_DATA_PATH_EXCEPTION; } } else if (elementToReturn.isJsonPrimitive()) { return Result.INVALID_DATA_PATH_EXCEPTION; } else { return Result.NO_SUCH_DATA_PATH_EXCEPTION; } } if (elementToReturn.isJsonNull()) { return Result.JSON_NULL_EXCEPTION; } return Result.success(elementToReturn); } }
From source file:com.flipkart.android.proteus.toolbox.Utils.java
License:Apache License
public static JsonElement merge(JsonElement oldJson, JsonElement newJson, boolean useCopy, Gson gson) { JsonElement newDataElement;//from w w w. ja v a2 s . c o m JsonArray oldArray; JsonArray newArray; JsonElement oldArrayItem; JsonElement newArrayItem; JsonObject oldObject; if (oldJson == null || oldJson.isJsonNull()) { return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson; } if (newJson == null || newJson.isJsonNull()) { newJson = JsonNull.INSTANCE; return newJson; } if (newJson.isJsonPrimitive()) { JsonPrimitive value; if (!useCopy) { return newJson; } if (newJson.getAsJsonPrimitive().isBoolean()) { value = new JsonPrimitive(newJson.getAsBoolean()); } else if (newJson.getAsJsonPrimitive().isNumber()) { value = new JsonPrimitive(newJson.getAsNumber()); } else if (newJson.getAsJsonPrimitive().isString()) { value = new JsonPrimitive(newJson.getAsString()); } else { value = newJson.getAsJsonPrimitive(); } return value; } if (newJson.isJsonArray()) { if (!oldJson.isJsonArray()) { return useCopy ? gson.fromJson(newJson, JsonArray.class) : newJson; } else { oldArray = oldJson.getAsJsonArray(); newArray = newJson.getAsJsonArray(); if (oldArray.size() > newArray.size()) { while (oldArray.size() > newArray.size()) { oldArray.remove(oldArray.size() - 1); } } for (int index = 0; index < newArray.size(); index++) { if (index < oldArray.size()) { oldArrayItem = oldArray.get(index); newArrayItem = newArray.get(index); oldArray.set(index, merge(oldArrayItem, newArrayItem, useCopy, gson)); } else { oldArray.add(newArray.get(index)); } } } } else if (newJson.isJsonObject()) { if (!oldJson.isJsonObject()) { return useCopy ? gson.fromJson(newJson, JsonObject.class) : newJson; } else { oldObject = oldJson.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : newJson.getAsJsonObject().entrySet()) { newDataElement = merge(oldObject.get(entry.getKey()), entry.getValue(), useCopy, gson); oldObject.add(entry.getKey(), newDataElement); } } } else { return useCopy ? gson.fromJson(newJson, JsonElement.class) : newJson; } return oldJson; }
From source file:com.gcm.samples.friendlyping.FriendlyPingServer.java
License:Open Source License
/** * Send client list to newly registered client. When a new client is registered, that client must * be informed about the other registered clients. * * @param client Newly registered client. *//*from ww w . j a v a 2s .c om*/ private void sendClientList(Client client) { ArrayList<Client> clientList = new ArrayList(); for (Entry<String, Client> clientEntry : clientMap.entrySet()) { Client currentClient = clientEntry.getValue(); if (currentClient.registrationToken != client.registrationToken) { clientList.add(currentClient); } } JsonElement clientElements = gson.toJsonTree(clientList, new TypeToken<Collection<Client>>() { }.getType()); if (clientElements.isJsonArray()) { JsonObject jSendClientList = new JsonObject(); JsonObject jData = new JsonObject(); jData.addProperty(ACTION_KEY, SEND_CLIENT_LIST); jData.add(CLIENTS_KEY, clientElements); jSendClientList.add(DATA_KEY, jData); friendlyGcmServer.send(client.registrationToken, jSendClientList); } }
From source file:com.getperka.flatpack.codexes.DynamicCodex.java
License:Apache License
/** * Attempt to infer the type from the JsonElement presented. * <ul>/*from w ww .j av a 2 s . co m*/ * <li>boolean -> {@link Boolean} * <li>number -> {@link BigDecimal} * <li>string -> {@link HasUuid} or {@link String} * <li>array -> {@link ListCodex} * <li>object -> {@link StringMapCodex} * </ul> */ @Override public Object readNotNull(JsonElement element, DeserializationContext context) throws Exception { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { // Always return numbers as BigDecimals for consistency return primitive.getAsBigDecimal(); } else { String value = primitive.getAsString(); // Interpret UUIDs as entity references if (UUID_PATTERN.matcher(value).matches()) { UUID uuid = UUID.fromString(value); HasUuid entity = context.getEntity(uuid); if (entity != null) { return entity; } } return value; } } else if (element.isJsonArray()) { return listCodex.get().readNotNull(element, context); } else if (element.isJsonObject()) { return mapCodex.get().readNotNull(element, context); } context.fail(new UnsupportedOperationException("Cannot infer data type for " + element.toString())); return null; }
From source file:com.github.GsonPrettyPrinter.java
License:Open Source License
private List<String> toStringList(final JsonElement je) { if (je == null || je.isJsonNull()) return new ArrayList<String>(Arrays.asList(new String[] { "null" })); if (je.isJsonPrimitive()) return Collections.singletonList(je.getAsJsonPrimitive().toString()); if (je.isJsonArray()) { final JsonArray jsonArray = je.getAsJsonArray(); return arrayToStringList(jsonArray); } else if (je.isJsonObject()) { final JsonObject jsonObject = je.getAsJsonObject(); return objectToStringList(jsonObject); }//from w w w. java 2 s. c o m throw new RuntimeException("Unsupported Json element: " + je.getClass().getName()); }
From source file:com.github.jtail.sterren.ValidatingAdapterFactory.java
License:Apache License
private <T> T validate(T object, Optional<JsonElement> errors) { JsonElement structuralErrors = errors.orElse(new JsonObject()); JsonElement feedback; if (object != null) { Set<ConstraintViolation<T>> violations = validator.validate(object); feedback = converter.merge(violations, structuralErrors); } else {/*from ww w . ja va 2 s . co m*/ feedback = structuralErrors; } if (feedback.isJsonArray() || feedback.getAsJsonObject().entrySet().isEmpty()) { return object; } else { throw new ObjectValidationException("Validation failed", feedback); } }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
License:Apache License
private List<String> getAuthorities(JsonObject userObject) { List<String> authorities = new ArrayList<String>(); if (!userObject.has(AUTHORITIES)) { throw new AlfrescoParseException("Json response is authorities."); }//from w ww .ja v a 2 s. co m JsonElement authoritiesElement = userObject.get(AUTHORITIES); if (!authoritiesElement.isJsonArray()) { throw new AlfrescoParseException( "Authorities must be a json array. It was: " + authoritiesElement.toString()); } JsonArray authoritiesArray = authoritiesElement.getAsJsonArray(); for (JsonElement authorityElement : authoritiesArray) { if (!authorityElement.isJsonPrimitive()) { throw new AlfrescoParseException( "Authority entry must be a string. It was: " + authoritiesElement.toString()); } JsonPrimitive authorityPrimitive = authorityElement.getAsJsonPrimitive(); if (!authorityPrimitive.isString()) { throw new AlfrescoParseException( "Authority entry must be a string. It was: " + authoritiesElement.toString()); } authorities.add(authorityPrimitive.getAsString()); } return authorities; }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
License:Apache License
private List<AlfrescoUser> usersFromHttpEntity(HttpEntity entity) throws IOException { Reader entityReader = new InputStreamReader(entity.getContent()); JsonElement responseObject = gson.fromJson(entityReader, JsonElement.class); if (!responseObject.isJsonArray()) { throw new AlfrescoParseException("Users must be a json array."); }/*from w w w . java 2 s . c o m*/ List<AlfrescoUser> users = new ArrayList<AlfrescoUser>(); JsonArray usersArray = responseObject.getAsJsonArray(); for (JsonElement userElement : usersArray) { if (!userElement.isJsonObject()) { throw new AlfrescoParseException("User must be a json object."); } AlfrescoUser user = getUser(userElement.getAsJsonObject()); users.add(user); } return users; }