List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:ch.ethz.inf.vs.hypermedia.corehal.OptionalListDeserializer.java
License:Open Source License
@Override public OptionalList deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { OptionalList list = new OptionalList(); Type elementType = ((ParameterizedType) typeOfT).getActualTypeArguments()[0]; if (json.isJsonArray()) { for (JsonElement el : json.getAsJsonArray()) { list.add(context.deserialize(el, elementType)); }//from w ww.j a v a 2 s . co m } else { list.add(context.deserialize(json, elementType)); } return list; }
From source file:cheerPackage.JSONUtils.java
public static String getValueFromArrayElement(String jsonArrayString, String attribute, int index) throws MalformedJsonException, JsonSyntaxException { JsonParser parser = new JsonParser(); JsonElement json = parser.parse(jsonArrayString); if (json.isJsonArray()) { JsonElement firstItem = json.getAsJsonArray().get(index); if (firstItem.isJsonPrimitive()) { return firstItem.getAsString(); } else if (firstItem.isJsonObject()) { return firstItem.getAsJsonObject().get(attribute).getAsString(); } else {// w w w.ja v a 2 s. co m System.out.println( "This function only goes in 1 level (from Array to Object in array, or primitive)."); return null; } } else { System.out.println("This function only works on Json arrays."); return null; } }
From source file:classes.analysis.Analysis.java
License:Open Source License
private String getJsonElementAsString(JsonElement element) { String value = ""; if (element == null) { return "-"; } else if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); for (JsonElement subelement : array) { value = this.getJsonElementAsString(subelement); }/*from w ww.j a v a2 s. co m*/ } else if (element.isJsonObject()) { JsonObject object = element.getAsJsonObject(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { value += entry.getKey() + ":" + this.getJsonElementAsString(entry.getValue()); } } else if (element.isJsonPrimitive()) { value += element.toString().replaceAll("\"", "") + "\n"; } return value; }
From source file:classes.analysis.Analysis.java
License:Open Source License
private String generateXMLContent(JsonElement jsonCode, int level) { String content = ""; if (jsonCode.isJsonPrimitive()) { content += jsonCode.getAsString(); } else if (jsonCode.isJsonArray()) { content += "\n"; for (JsonElement subelement : jsonCode.getAsJsonArray()) { content += this.generateXMLContent(subelement, level + 1); }/* w w w . j av a 2 s .c o m*/ content += "\n"; content += String.join("", Collections.nCopies(level - 1, "\t")); } else if (jsonCode.isJsonObject()) { for (Map.Entry<String, JsonElement> entry : jsonCode.getAsJsonObject().entrySet()) { content += String.join("", Collections.nCopies(level, "\t")) + "<" + entry.getKey() + ">" + this.generateXMLContent(entry.getValue(), level + 1) + "</" + entry.getKey() + ">\n"; } } return content; }
From source file:classes.analysis.Step.java
License:Open Source License
protected static String getParameterDescription(JsonElement parameter, int level) { if (parameter.isJsonPrimitive()) { return parameter.getAsString() + "\n"; }// w w w . j a va2 s. c o m if (parameter.isJsonArray()) { String description = ""; String prefix = ""; for (int i = 0; i < level; i++) { prefix += " "; } for (JsonElement element : parameter.getAsJsonArray()) { description += prefix + Step.getParameterDescription(element, level + 1); } return description; } if (parameter.isJsonObject()) { String description = ""; String prefix = ""; for (int i = 0; i < level; i++) { prefix += " "; } for (Map.Entry<String, JsonElement> member : parameter.getAsJsonObject().entrySet()) { description += prefix + "- " + member.getKey() + ": " + Step.getParameterDescription(member.getValue(), level + 1); } return description; } return ""; }
From source file:club.jmint.mifty.service.MiftyService.java
License:Apache License
public String callProxy(String method, String params, boolean isEncrypt) throws TException { //parse parameters and verify signature CrossLog.logger.debug("callProxy: " + method + "(in: " + params + ")"); JsonObject ip;/*from w w w . j a v a 2 s .co m*/ try { ip = parseInputParams(params, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } //extract all parameters HashMap<String, String> inputMap = new HashMap<String, String>(); Iterator<Entry<String, JsonElement>> it = ip.entrySet().iterator(); Entry<String, JsonElement> en = null; String key; JsonElement je; while (it.hasNext()) { en = it.next(); key = en.getKey(); je = en.getValue(); if (je.isJsonArray()) { inputMap.put(key, je.getAsJsonArray().toString()); //System.out.println(je.getAsJsonArray().toString()); } else if (je.isJsonNull()) { inputMap.put(key, je.getAsJsonNull().toString()); //System.out.println(je.getAsJsonNull().toString()); } else if (je.isJsonObject()) { inputMap.put(key, je.getAsJsonObject().toString()); //System.out.println(je.getAsJsonObject().toString()); } else if (je.isJsonPrimitive()) { inputMap.put(key, je.getAsJsonPrimitive().getAsString()); //System.out.println(je.getAsJsonPrimitive().toString()); } else { //unkown type; } } //execute specific method Method[] ma = this.getClass().getMethods(); int idx = 0; for (int i = 0; i < ma.length; i++) { if (ma[i].getName().equals(method)) { idx = i; break; } } HashMap<String, String> outputMap = null; try { Method m = this.getClass().getDeclaredMethod(method, ma[idx].getParameterTypes()); outputMap = (HashMap<String, String>) m.invoke(this, inputMap); CrossLog.logger.debug("callProxy: " + method + "() executed."); } catch (NoSuchMethodException nsm) { CrossLog.logger.error("callProxy: " + method + "() not found."); CrossLog.printStackTrace(nsm); return buildOutputError(ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getCode(), ErrorCode.CROSSING_ERR_INTERFACE_NOT_FOUND.getInfo()); } catch (Exception e) { CrossLog.logger.error("callProxy: " + method + "() executed with exception."); CrossLog.printStackTrace(e); if (e instanceof CrossException) { return buildOutputByCrossException((CrossException) e); } else { return buildOutputError(ErrorCode.COMMON_ERR_UNKOWN.getCode(), ErrorCode.COMMON_ERR_UNKOWN.getInfo()); } } //if got error then return immediately String ec = outputMap.get("errorCode"); String ecInfo = outputMap.get("errorInfo"); if ((ec != null) && (!ec.isEmpty())) { return buildOutputError(Integer.parseInt(ec), ecInfo); } //build response parameters JsonObject op = new JsonObject(); Iterator<Entry<String, String>> ito = outputMap.entrySet().iterator(); Entry<String, String> eno = null; JsonParser jpo = new JsonParser(); JsonElement jeo = null; while (ito.hasNext()) { eno = ito.next(); try { jeo = jpo.parse(eno.getValue()); } catch (JsonSyntaxException e) { // MyLog.logger.error("callProxy: Malformed output parameters["+eno.getKey()+"]."); // return buildOutputError(ErrorCode.COMMON_ERR_PARAM_MALFORMED.getCode(), // ErrorCode.COMMON_ERR_PARAM_MALFORMED.getInfo()); //we do assume that it should be a common string jeo = new JsonPrimitive(eno.getValue()); } op.add(eno.getKey(), jeo); } String output = null; try { output = buildOutputParams(op, isEncrypt); } catch (CrossException ce) { return buildOutputByCrossException(ce); } CrossLog.logger.debug("callProxy: " + method + "(out: " + output + ")"); return output; }
From source file:co.cask.cdap.common.zookeeper.coordination.ResourceAssignmentTypeAdapter.java
License:Apache License
@Override public ResourceAssignment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("Expect a json object, got " + json); }/*from w w w. j a va 2 s. c o m*/ JsonObject jsonObj = json.getAsJsonObject(); String name = jsonObj.get("name").getAsString(); Multimap<Discoverable, PartitionReplica> assignments = TreeMultimap .create(DiscoverableComparator.COMPARATOR, PartitionReplica.COMPARATOR); JsonArray assignmentsJson = context.deserialize(jsonObj.get("assignments"), JsonArray.class); for (JsonElement element : assignmentsJson) { if (!element.isJsonArray()) { throw new JsonParseException("Expect a json array, got " + element); } JsonArray entryJson = element.getAsJsonArray(); if (entryJson.size() != 2) { throw new JsonParseException("Expect json array of size = 2, got " + entryJson.size()); } Discoverable key = context.deserialize(entryJson.get(0), Discoverable.class); PartitionReplica value = context.deserialize(entryJson.get(1), PartitionReplica.class); assignments.put(key, value); } return new ResourceAssignment(name, assignments); }
From source file:co.vaughnvernon.tradercommon.media.AbstractJSONMediaReader.java
License:Apache License
protected JsonElement navigateTo(JsonObject aStartingJsonObject, String... aKeys) { if (aKeys.length == 0) { throw new IllegalArgumentException("Must specify one or more keys."); } else if (aKeys.length == 1 && (aKeys[0].startsWith("/") || aKeys[0].contains("."))) { aKeys = this.parsePath(aKeys[0]); }/*ww w . j a v a 2s .co m*/ int keyIndex = 1; JsonElement element = this.elementFrom(aStartingJsonObject, aKeys[0]); if (!element.isJsonNull() && !element.isJsonPrimitive() && !element.isJsonArray()) { JsonObject object = element.getAsJsonObject(); for (; element != null && !element.isJsonPrimitive() && keyIndex < aKeys.length; ++keyIndex) { element = this.elementFrom(object, aKeys[keyIndex]); if (!element.isJsonPrimitive()) { element = this.elementFrom(object, aKeys[keyIndex]); if (element.isJsonNull()) { element = null; } else { object = element.getAsJsonObject(); } } } } if (element != null) { if (!element.isJsonNull()) { if (keyIndex != aKeys.length) { throw new IllegalArgumentException("Last name must reference a simple value."); } } else { element = null; } } return element; }
From source file:com.addthis.hydra.task.source.bundleizer.GsonBundleizer.java
License:Apache License
public ValueObject fromGson(JsonElement gson) { if (gson.isJsonNull()) { return null; } else if (gson.isJsonObject()) { JsonObject object = gson.getAsJsonObject(); ValueMap map = ValueFactory.createMap(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { map.put(entry.getKey(), fromGson(entry.getValue())); }//ww w. j a v a2 s. c o m return map; } else if (gson.isJsonArray()) { JsonArray gsonArray = gson.getAsJsonArray(); ValueArray valueArray = ValueFactory.createArray(gsonArray.size()); for (JsonElement arrayElement : gsonArray) { valueArray.add(fromGson(arrayElement)); } return valueArray; } else { JsonPrimitive primitive = gson.getAsJsonPrimitive(); if (primitive.isNumber()) { return ValueFactory.create(primitive.getAsDouble()); } else { return ValueFactory.create(primitive.getAsString()); } } }
From source file:com.adobe.acs.commons.json.JsonObjectUtil.java
License:Apache License
public static boolean isSingularElement(JsonElement elem) { return elem.isJsonPrimitive() || (elem.isJsonArray() && elem.getAsJsonArray().size() <= 1); }