List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:donky.microsoft.aspnet.signalr.client.transport.TransportHelper.java
License:Open Source License
public static MessageResult processReceivedData(String data, ConnectionBase connection) { Logger logger = connection.getLogger(); MessageResult result = new MessageResult(); if (data == null) { return result; }// w ww.j a v a2s.c o m data = data.trim(); if ("".equals(data)) { return result; } JsonObject json = null; try { json = connection.getJsonParser().parse(data).getAsJsonObject(); } catch (Exception e) { connection.onError(e, false); return result; } if (json.entrySet().size() == 0) { return result; } if (json.get("I") != null) { logger.log("Invoking message received with: " + json.toString(), LogLevel.Verbose); connection.onReceived(json); } else { // disconnected if (json.get("D") != null) { if (json.get("D").getAsInt() == 1) { logger.log("Disconnect message received", LogLevel.Verbose); result.setDisconnect(true); return result; } } // should reconnect if (json.get("T") != null) { if (json.get("T").getAsInt() == 1) { logger.log("Reconnect message received", LogLevel.Verbose); result.setReconnect(true); } } if (json.get("G") != null) { String groupsToken = json.get("G").getAsString(); logger.log("Group token received: " + groupsToken, LogLevel.Verbose); connection.setGroupsToken(groupsToken); } JsonElement messages = json.get("M"); if (messages != null && messages.isJsonArray()) { if (json.get("C") != null) { String messageId = json.get("C").getAsString(); logger.log("MessageId received: " + messageId, LogLevel.Verbose); connection.setMessageId(messageId); } JsonArray messagesArray = messages.getAsJsonArray(); int size = messagesArray.size(); for (int i = 0; i < size; i++) { JsonElement message = messagesArray.get(i); JsonElement processedMessage = null; logger.log("Invoking OnReceived with: " + processedMessage, LogLevel.Verbose); connection.onReceived(message); } } if (json.get("S") != null) { if (json.get("S").getAsInt() == 1) { logger.log("Initialization message received", LogLevel.Information); result.setInitialize(true); } } } return result; }
From source file:edu.isi.karma.service.json.JsonManager.java
License:Apache License
private static void recursiveParse(JsonElement jse, Element element) { if (jse.isJsonObject()) { JsonObject j = jse.getAsJsonObject(); Set<Entry<String, JsonElement>> set = j.entrySet(); // System.out.println(set.size()); Iterator<Entry<String, JsonElement>> iter = set.iterator(); while (iter.hasNext()) { Entry<String, JsonElement> entry = iter.next(); Element e = new Element(); e.setKey(entry.getKey());//from w w w . ja va2s . co m // System.out.println("create " + e.getKey()); e.setValue(new ArrayValue()); e.setValueType(ValueType.ARRAY); recursiveParse(entry.getValue(), e); // System.out.println("element " + element.getKey()); e.setParent(element); ((ArrayValue) element.getValue()).getElements().add(e); // System.out.println("e " + e.getKey()); } } else if (jse.isJsonArray()) { JsonArray j = jse.getAsJsonArray(); Iterator<JsonElement> iter = j.iterator(); while (iter.hasNext()) { Element e = new Element(); e.setKey(""); e.setValue(new ArrayValue()); e.setValueType(ValueType.ARRAY); recursiveParse(iter.next(), e); e.setParent(element); ((ArrayValue) element.getValue()).getElements().add(e); } } else if (jse.isJsonPrimitive()) { element.setValueType(ValueType.SINGLE); element.setValue(new SingleValue(jse.toString())); // System.out.println(jse.getAsString()); } }
From source file:edu.isi.wings.portal.classes.JsonHandler.java
License:Apache License
public Binding deserialize(JsonElement el, Type typeOfSrc, JsonDeserializationContext context) { if (el.isJsonArray()) { Binding b = new Binding(); for (JsonElement cel : el.getAsJsonArray()) { b.add((Binding) context.deserialize(cel, Binding.class)); }//from w ww . j a va 2s . c o m return b; } else { JsonObject obj = (JsonObject) el; if (obj.get("type") == null) return null; String type = obj.get("type").getAsString(); if ("uri".equals(type)) return new Binding(obj.get("id").getAsString()); else if ("literal".equals(type)) { String datatype = obj.get("datatype") != null ? obj.get("datatype").getAsString() : KBUtils.XSD + "string"; return new ValueBinding(obj.get("value").getAsString(), datatype); } } return null; }
From source file:edu.mit.media.funf.config.ConfigRewriteUtil.java
License:Open Source License
/** * Rewrites the filter array denoted by "@filters" to a "filters" member * with nested filters, in the order of their appearance in the array. * //from ww w.ja v a2 s.c o m * If the baseObj is not a CompositeDataSource, converts it into one, and * pushing the "@probe" annotation (if it exists) to the "source" field. * * If the entire filter class name is not specified, it will be prefixed by * FILTER_PREFIX. * * eg. * { "@probe": ".ActivityProbe", * "sensorDelay": "FASTEST", * "@filters": [{ "@type": ".KeyValueFilter", "matches": { "motionState": "Driving" } }, * { "@type": ".ProbabilityFilter", "probability": 0.5 } ] * } * * will be rewritten to * * { "@type": "edu.mit.media.funf.datasource.CompositeDataSource", * "source": { "@probe": ".ActivityProbe", "sensorDelay": "FASTEST" }, * "filters": { "@type": "edu.mit.media.funf.filter.KeyValueFilter", * "matches": { "motionState": "Driving" } * "listener": { "@type": "edu.mit.media.funf.filter.ProbabilityFilter", * "probability": 0.5 } } * } * * @param baseObj */ public static JsonObject rewriteFiltersAnnotation(JsonObject baseObj) { if (baseObj == null) return null; JsonElement filterEl = baseObj.remove(FILTER); JsonObject filterObj = null; if (filterEl.isJsonArray()) { for (JsonElement filterIter : filterEl.getAsJsonArray()) { if (filterIter.isJsonObject()) { // Add the filter class name prefix if not specified. addTypePrefix(filterIter.getAsJsonObject(), FILTER_PREFIX); } } filterObj = new JsonObject(); filterObj.addProperty(TYPE, COMPOSITE_FILTER); filterObj.add("filters", filterEl.getAsJsonArray()); } else { filterObj = filterEl.getAsJsonObject(); } // Add the filter class name prefix if not specified. addTypePrefix(filterObj.getAsJsonObject(), FILTER_PREFIX); // Insert the filter object denoted by "@filter" to the existing // "filter" field. insertFilter(baseObj, filterObj); // If the baseObj is not a data source, convert it into CompositeDataSource. if (!isDataSourceObject(baseObj)) { JsonObject dataSourceObj = new JsonObject(); dataSourceObj.addProperty(TYPE, COMPOSITE_DS); dataSourceObj.add(FILTER_FIELD_NAME, baseObj.remove(FILTER_FIELD_NAME)); if (baseObj.has(ACTION)) { dataSourceObj.add(ACTION, baseObj.remove(ACTION)); } // The remaining fields of baseObj should be "@probe" annotation and // probe parameters. dataSourceObj.add(SOURCE_FIELD_NAME, baseObj); return dataSourceObj; } else { return baseObj; } }
From source file:edu.mit.media.funf.json.JsonUtils.java
License:Open Source License
/** * Sort all elements in Json objects, to ensure that they are identically serialized. * @param el/*w w w. j a v a2s. c o m*/ * @return */ public static JsonElement deepSort(JsonElement el) { if (el == null) { return null; } else if (el.isJsonArray()) { JsonArray sortedArray = new JsonArray(); for (JsonElement subEl : (JsonArray) el) { sortedArray.add(deepSort(subEl)); } return sortedArray; } else if (el.isJsonObject()) { List<Entry<String, JsonElement>> entrySet = new ArrayList<Entry<String, JsonElement>>( ((JsonObject) el).entrySet()); Collections.sort(entrySet, JSON_OBJECT_ENTRY_SET_COMPARATOR); JsonObject sortedObject = new JsonObject(); for (Entry<String, JsonElement> entry : entrySet) { sortedObject.add(entry.getKey(), deepSort(entry.getValue())); } return sortedObject; } else { return el; } }
From source file:edu.wfu.inotado.helper.MarshalHelper.java
License:Apache License
@SuppressWarnings({ "rawtypes", "unchecked" }) public <T> T unmarshalJson(String json, Class<T> type) { T obj = null;//from w w w . j av a 2 s .c om Gson gson = new Gson(); if (StringUtils.isNotEmpty(json)) { JsonElement element = gsonParser.parse(json); if (element.isJsonArray()) { // process array JsonArray array = element.getAsJsonArray(); List list = new ArrayList(); for (int i = 0; i < array.size(); i++) { list.add(gson.fromJson(array.get(i), type)); } obj = (T) list; } else { // process single element obj = (T) gson.fromJson(json, type); } } else { log.warn("The input Json string is empty"); } return obj; }
From source file:elaborate.tag_analysis.oosm.impl.gson.BaseInterfaceDeserializer.java
@Override public T deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { try {// w w w.j a va2s .c o m T object = (T) this.createInstance(); JsonObject jsonObject = (JsonObject) je; Iterator<Entry<String, JsonElement>> it = jsonObject.entrySet().iterator(); //iterate through class fields while (it.hasNext()) { try { Entry<String, JsonElement> entry = it.next(); JsonElement jsonElement = entry.getValue(); Field field = getField(entry.getKey()); if (jsonElement.isJsonArray()) { Object arrayValue = this.processArrayElement(entry.getKey(), jsonElement.getAsJsonArray(), field, jdc); PropertyUtils.setProperty(object, entry.getKey(), arrayValue); } else { Object normalValue = this.processNormalElement(entry.getKey(), jsonElement, field, jdc); PropertyUtils.setProperty(object, entry.getKey(), normalValue); // if(field.getName().equals("type")){ // System.out.println(( (OOSMElement)object ).getType()); // } } } catch (Exception ex) { //System.out.println(object.getClass()); Logger.getLogger(BaseInterfaceDeserializer.class.getName()).log(Level.SEVERE, null, ex); } } return object; } catch (Exception ex) { Logger.getLogger(BaseInterfaceDeserializer.class.getName()).log(Level.SEVERE, null, ex); throw new JsonParseException(ex); } }
From source file:exp.server.SDProcess.java
License:Open Source License
private static void prArray(JsonElement jelement) { System.out.println("------------------------Array---------------------------"); JsonArray jarray = jelement.getAsJsonArray(); for (JsonElement jobjecte : jarray) { if (jobjecte.isJsonObject()) { prObject(jobjecte);//ww w . j ava2 s . co m } else if (jobjecte.isJsonArray()) { prArray(jobjecte); } else { System.out.println("sathish"); } } }
From source file:fr.inria.atlanmod.discoverer.JsonDiscoverer.java
License:Open Source License
/** * Creates a new structuralFeature out from a pairId/Value * //from www . jav a 2s .c o m * @param pairId * @param value * @param eClass */ private void createStructuralFeature(String pairId, JsonElement value, int lowerBound, EClass eClass) { EStructuralFeature eStructuralFeature = null; EClassifier type = mapType(pairId, value); if (type instanceof EDataType) { eStructuralFeature = EcoreFactory.eINSTANCE.createEAttribute(); } else if (type instanceof EClass) { eStructuralFeature = EcoreFactory.eINSTANCE.createEReference(); ((EReference) eStructuralFeature).setContainment(true); } if (value.isJsonArray()) { eStructuralFeature.setUpperBound(-1); } if (eStructuralFeature != null) { eStructuralFeature.setName(pairId); eStructuralFeature.setLowerBound(lowerBound); eStructuralFeature.setEType(mapType(pairId, value)); AnnotationHelper.INSTANCE.increaseTotalFound(eStructuralFeature); eClass.getEStructuralFeatures().add(eStructuralFeature); LOGGER.fine("[createStructuralFeature] " + eStructuralFeature.getClass().getSimpleName() + " created with name " + pairId + " type " + eStructuralFeature.getEType().getName() + " and lower bound " + lowerBound); if (type instanceof EClass) { //create eOpposite EReference eOppositeFeature = EcoreFactory.eINSTANCE.createEReference(); eOppositeFeature.setName(eClass.getName().toLowerCase()); eOppositeFeature.setLowerBound(1); eOppositeFeature.setUpperBound(1); eOppositeFeature.setEType(eClass); eOppositeFeature.setEOpposite(((EReference) eStructuralFeature)); EClass opposite = (EClass) type; opposite.getEStructuralFeatures().add(eOppositeFeature); ((EReference) eStructuralFeature).setEOpposite(eOppositeFeature); } } }
From source file:fr.inria.atlanmod.discoverer.JsonDiscoverer.java
License:Open Source License
/** * Maps json types into ecore types// w ww .ja va 2s . c om * * @param id * @param value * @return */ private EClassifier mapType(String id, JsonElement value) { if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isString()) { return EcorePackage.Literals.ESTRING; } else if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isNumber()) { return EcorePackage.Literals.EINT; } else if (value.isJsonPrimitive() && value.getAsJsonPrimitive().isBoolean()) { return EcorePackage.Literals.EBOOLEAN; } else if (value.isJsonArray()) { JsonArray arrayValue = value.getAsJsonArray(); if (arrayValue.size() > 0) { EClassifier generalArrayType = mapType(digestId(id), arrayValue.get(0)); for (int i = 1; i < arrayValue.size(); i++) { JsonElement arrayElement = arrayValue.get(i); EClassifier arrayType = mapType(digestId(id), arrayElement); if (generalArrayType != arrayType) { LOGGER.finer( "[mapType] Detected array multi-typed, using fallback type (String) for " + id); return EcorePackage.Literals.ESTRING; } } return generalArrayType; } } else if (value.isJsonObject()) { return discoverMetaclass(digestId(id), value.getAsJsonObject()); } LOGGER.finer("[mapType] Type not discovererd for " + id); return EcorePackage.Literals.ESTRING; }