List of usage examples for com.google.gson JsonElement getAsJsonArray
public JsonArray getAsJsonArray()
From source file:com.kotcrab.vis.editor.serializer.json.IntArrayJsonSerializer.java
License:Apache License
@Override public IntArray deserialize(JsonElement j, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonArray json = j.getAsJsonArray(); IntArray intArray = new IntArray(json.size()); for (int i = 0; i < json.size(); i++) { intArray.add(json.get(i).getAsInt()); }/*from ww w . j a v a 2s . c o m*/ return intArray; }
From source file:com.kotcrab.vis.editor.serializer.json.IntMapJsonSerializer.java
License:Apache License
@Override public IntMap<T> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonArray jsonArray = json.getAsJsonArray(); IntMap<T> intMap = new IntMap<>(jsonArray.size()); for (JsonElement element : jsonArray) { JsonObject object = element.getAsJsonObject(); Entry<String, JsonElement> entry = object.entrySet().iterator().next(); int mapKey = Integer.parseInt(entry.getKey()); Class<?> mapObjectClass = GsonUtils.readClassProperty(object, context); intMap.put(mapKey, context.deserialize(entry.getValue(), mapObjectClass)); }/*from ww w . ja v a2 s. c o m*/ return intMap; }
From source file:com.kotcrab.vis.editor.serializer.json.ObjectMapJsonSerializer.java
License:Apache License
@Override public ObjectMap<K, V> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonArray jsonArray = json.getAsJsonArray(); ObjectMap<K, V> objMap = new ObjectMap<>(jsonArray.size()); for (JsonElement element : jsonArray) { JsonObject object = element.getAsJsonObject(); K key = context.deserialize(object.get("key"), GsonUtils.readClassProperty(object, context, PROPERTY_CLASS_KEY)); V value = context.deserialize(object.get("value"), GsonUtils.readClassProperty(object, context, PROPERTY_CLASS_VALUE)); objMap.put(key, value);/*from www .ja v a 2s . c o m*/ } return objMap; }
From source file:com.liferay.hackaday.lunchhangout.model.Poll.java
License:Open Source License
public String getVotesCount() { int votesCount = 0; JsonElement votes = getVotes(); if (votes != null) { if (votes.isJsonPrimitive()) { votesCount = 1;/*from w ww . j a v a 2s. c o m*/ } else { votesCount = votes.getAsJsonArray().size(); } } return String.valueOf(votesCount); }
From source file:com.make.json2java.ClassField.java
License:Apache License
/** * Based on the seen json values, infer a type for this field. * Strings are mapped to String. numbers are preferred mapped to ints, then longs and finally as doubles. *//*from w w w . jav a 2 s . c om*/ private InferredType inferType(Iterable<JsonElement> jsonValues, String type, boolean isArrayType) { if (mappedType) return new InferredType(type, isArrayType); InferredType inferredType = new InferredType(type, isArrayType); for (JsonElement jsonValue : jsonValues) { if (jsonValue instanceof JsonPrimitive) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (isBooleanValue(primitive)) { inferredType = new InferredType("boolean", false); } else if (primitive.isString()) { inferredType = new InferredType("String", false); } else if (primitive.isNumber()) { double number = primitive.getAsDouble(); boolean isWholeNumber = number - Math.ceil(number) == 0; if (isWholeNumber) { // int is preferred over long so look for that long longValue = (long) number; boolean isLargerThanInt = longValue > Integer.MAX_VALUE || longValue < Integer.MIN_VALUE; if (isLargerThanInt && !inferredType.type.equals("double")) { // some other value was a floating point inferredType = new InferredType("long", false); } else { // some other jsonValue was big enough to fit in long if (!inferredType.equals("long") && !inferredType.equals("double")) { inferredType = new InferredType("int", false); } } } else { // double is preferred over float inferredType = new InferredType("double", false); } } } else if (jsonValue instanceof JsonArray) { this.isArrayType = true; inferredType = new InferredType(inferType(jsonValue.getAsJsonArray(), type, false).type, true); } } return inferredType; }
From source file:com.make.json2java.Json2Java.java
License:Apache License
private void processJson(String pkg, String className, CustomMappings mappings, JsonElement root) throws IOException { while (!(root instanceof JsonObject)) { if (root instanceof JsonArray) { for (JsonElement arrayElement : root.getAsJsonArray()) { processJson(pkg, className, mappings, arrayElement); }//from w ww.j a v a 2 s. co m return; // nothing much needs to be done } else if (root instanceof JsonPrimitive) { return; // can't generate classes for a primitive } } if (root instanceof JsonObject) { ClassDefCollection classes = new ClassDefCollection(); generateClasses(classes, root.getAsJsonObject(), pkg, className); classes.transform(mappings); this.classes.merge(classes); } }
From source file:com.make.json2java.Json2Java.java
License:Apache License
private void generateClasses(ClassDefCollection classes, JsonObject root, String pkg, String className) throws IOException { ClassDefinition classDef = classes.addClassDefinition(pkg, className); for (Map.Entry<String, JsonElement> element : root.entrySet()) { String name = element.getKey(); JsonElement value = element.getValue(); String type = Utils.lowerCaseUnderscoreToCamelCase(name, true); name = Utils.lowerCaseUnderscoreToCamelCase(name, false); if (value instanceof JsonPrimitive) { classDef.addField(new ClassField(name, value, type, false)); } else if (value instanceof JsonArray) { classDef.addImport("java.util.List"); classDef.addField(new ClassField(name, value, type, true)); JsonArray array = value.getAsJsonArray(); for (JsonElement arrayElement : array) { if (arrayElement instanceof JsonObject) { // Use all elements of the array generateClasses(classes, arrayElement.getAsJsonObject(), pkg, type); }/*ww w . j a va 2 s. c om*/ } } if (value instanceof JsonObject) { classDef.addField(new ClassField(name, value, type, false)); generateClasses(classes, value.getAsJsonObject(), pkg, type); } } }
From source file:com.mapper.yelp.YelpQueryManager.java
License:Apache License
public void parseBusinessTag(YelpBusiness business, JsonElement element) { for (final Entry<String, JsonElement> entry : element.getAsJsonObject().entrySet()) { final String key = entry.getKey(); final JsonElement value = entry.getValue(); if (key.contains(DISPLAY_PHONE_TAG)) { business.setPhoneNumber(value.getAsString()); } else if (key.contains(LOCATION_TAG)) { // Location for (final Entry<String, JsonElement> centry : value.getAsJsonObject().entrySet()) { final String k1 = centry.getKey(); final JsonElement v1 = centry.getValue(); if (k1.contains(ADDRESS_TAG)) { String address = ""; for (final JsonElement e2 : v1.getAsJsonArray()) { address += e2.getAsString() + " "; }/*from ww w . ja va 2 s . co m*/ business.setAddress(address); } else if (k1.contains(COORDINATE_TAG)) { for (final Entry<String, JsonElement> loc : v1.getAsJsonObject().entrySet()) { if (loc.getKey().contains(LATITUDE_TAG)) business.setLatitude(loc.getValue().getAsDouble()); else if (loc.getKey().contains(LONGITUDE_TAG)) business.setLongitude(loc.getValue().getAsDouble()); } } else if (k1.contains(CITY_TAG)) { business.setCity(v1.getAsString()); } else if (k1.contains(POSTAL_CODE_TAG)) { business.setPostalCode(v1.getAsInt()); } else if (k1.contains(STATE_TAG)) { business.setState(v1.getAsString()); } } } else if (key.contains(RATING_IMG_TAG)) { business.setRatingUrl(value.getAsString()); } else if (key.contains(REVIEW_TAG)) { business.setReviewCount(value.getAsInt()); } else if (key.contains(URL_TAG)) { business.setUrl(value.getAsString()); } else if (key.contains(NAME_TAG)) { business.setName(value.getAsString()); } else if (key.contains(IMAGE_URL_TAG)) { business.setImageUrl(value.getAsString()); } } }
From source file:com.master.aluca.fitnessmd.common.webserver.WebserverManager.java
License:Open Source License
@Override public void onDataAdded(String collectionName, String documentID, String fieldsJson) { Log.d(LOG_TAG, "Meteor DDP onDataAdded " + "Data added to <" + collectionName + "> in document <" + documentID + ">\n" + " Added: " + fieldsJson); if (collectionName.equalsIgnoreCase("users")) { String[] userDocIds = FitnessMDMeteor.getInstance().getDatabase().getCollection(collectionName) .getDocumentIds();/*from www. j a v a 2 s . c o m*/ Log.d(LOG_TAG, "userdocIds.length : " + userDocIds.length); for (int i = 0; i < userDocIds.length; i++) { InMemoryDocument userdoc = FitnessMDMeteor.getInstance().getDatabase().getCollection(collectionName) .getDocument(userDocIds[i]); Log.d(LOG_TAG, "field emails : " + userdoc.getField("emails").toString()); Gson gson = new Gson(); String json = gson.toJson(userdoc.getField("emails")); JsonParser parser = new JsonParser(); JsonElement element = parser.parse(json); JsonArray obj = element.getAsJsonArray(); for (int t = 0; t < obj.size(); t++) { JsonObject elem = obj.get(t).getAsJsonObject(); if (elem.has("address") && elem.get("address").getAsString().equalsIgnoreCase(userLoggingInEmail)) { mDB.updateUserID(userLoggingInEmail, documentID); } } } } else if (collectionName.equalsIgnoreCase("challenges")) { Log.d(LOG_TAG, "successfullySubscribedToChallenges : " + successfullySubscribedToChallenges); if (successfullySubscribedToChallenges) { InMemoryDocument challengeDoc = FitnessMDMeteor.getInstance().getDatabase() .getCollection(collectionName).getDocument(documentID); Intent sendChallenge = new Intent(Constants.NEW_CHALLENGE_INTENT); mContext.sendBroadcast(sendChallenge); Intent intent = new Intent(mContext, ChallengesActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext); mBuilder.setSmallIcon(R.drawable.icon_sm); mBuilder.setContentTitle( "New " + challengeDoc.getField(ChallengeDetails.TYPE).toString() + " challenge !"); mBuilder.setContentText("Difficulty : " + challengeDoc.getField(ChallengeDetails.DIFFICULTY)); mBuilder.setSubText("Description : " + challengeDoc.getField(ChallengeDetails.TEXT)); mBuilder.addAction(R.drawable.icon_sm, "Take it", pIntent); mBuilder.setContentIntent(pIntent); mBuilder.setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); } } else if (collectionName.equalsIgnoreCase("advices")) { Log.d(LOG_TAG, "successfullySubscribedToAdvices : " + successfullySubscribedToAdvices); if (successfullySubscribedToAdvices) { InMemoryDocument adviceDoc = FitnessMDMeteor.getInstance().getDatabase() .getCollection(collectionName).getDocument(documentID); Intent sendAdvice = new Intent(Constants.NEW_ADVICE_INTENT); mContext.sendBroadcast(sendAdvice); Intent intent = new Intent(mContext, AdvicesActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); PendingIntent pIntent = PendingIntent.getActivity(mContext, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext); mBuilder.setSmallIcon(R.drawable.icon_sm); mBuilder.setContentTitle( "Advice from " + adviceDoc.getField(AdviceDetails.OWNER).toString() + " !"); mBuilder.setContentText(adviceDoc.getField(AdviceDetails.MESSAGE).toString()); mBuilder.setSubText(adviceDoc.getField(AdviceDetails.TIMESTAMP).toString()); mBuilder.setContentIntent(pIntent); mBuilder.setAutoCancel(true); NotificationManager mNotificationManager = (NotificationManager) mContext .getSystemService(Context.NOTIFICATION_SERVICE); mNotificationManager.notify(0, mBuilder.build()); } } }
From source file:com.master.aluca.fitnessmd.common.webserver.WebserverManager.java
License:Open Source License
private synchronized void parseStatisticsData() { if (mDB.getConnectedUser() != null) { InMemoryDocument userdoc = FitnessMDMeteor.getInstance().getDatabase().getCollection("users") .getDocument(mDB.getConnectedUser().getDocId()); if (userdoc != null) { Gson gson = new Gson(); String json = gson.toJson(userdoc.getField("pedometerData")); if (json != null) { JsonParser parser = new JsonParser(); JsonElement element = parser.parse(json); JsonArray arr = element.getAsJsonArray(); LinkedHashMap<Long, Integer> map = new LinkedHashMap<>(); LinkedHashMap<Long, Integer> stats = new LinkedHashMap<>(); long startOfCurrentDay = Constants.getStartOfCurrentDay(); int totalSteps = 0; long[] daysAgo = new long[7]; for (int k = 7; k >= 1; k--) { daysAgo[k - 1] = startOfCurrentDay - (k * 24 * 60 * 60 * 1000); }// w ww. j av a2s. c o m // data is separated by hour index. concatenate data per day //Log.d(LOG_TAG,"map.size : " + map.size() + " entrySet.size : " + map.entrySet().size()); for (int t = 0; t < arr.size(); t++) { JsonObject elem = arr.get(t).getAsJsonObject(); JsonElement dayElement = elem.get("day"); if (dayElement != null) { Integer stepsForDay = map.get(dayElement.getAsLong()); //Log.d(LOG_TAG,"day : " + dayElement.getAsLong() + " steps : " + elem.get("steps").getAsInt() + " stepsForDay : " + stepsForDay); if (stepsForDay != null) { int steps = map.get(elem.get("day").getAsLong()); steps += elem.get("steps").getAsInt(); map.put(elem.get("day").getAsLong(), steps); } else { map.put(elem.get("day").getAsLong(), elem.get("steps").getAsInt()); } } totalSteps += elem.get("steps").getAsInt(); } int maxSteps = -1; long dayForMaxSteps = -1; AtomicBoolean valueInStatsChanged = new AtomicBoolean(false); Log.d(LOG_TAG, "savedStats.entrySet.size : " + savedStats.entrySet().size()); for (Map.Entry<Long, Integer> entry : map.entrySet()) { for (int l = 0; l < daysAgo.length; l++) { //Log.d(LOG_TAG,entry.getKey() + " : " + entry.getValue() + " daysAgo : " + daysAgo[l]); if (entry.getKey().longValue() == daysAgo[l]) { if (savedStats.entrySet().size() == 0) { valueInStatsChanged.set(true); } if (savedStats.containsKey(entry.getKey())) { Log.d(LOG_TAG, entry.getKey() + " : " + entry.getValue() + " savedStats : " + savedStats.get(entry.getKey().longValue())); if (savedStats.get(entry.getKey().longValue()) != entry.getValue() .longValue()) { Log.d(LOG_TAG, "values not equal : " + entry.getValue() + " savedStats : " + savedStats.get(entry.getKey().longValue())); valueInStatsChanged.set(true); } } else { savedStats.put(entry.getKey(), entry.getValue()); } stats.put(entry.getKey(), entry.getValue()); } } if (entry.getValue() > maxSteps) { maxSteps = entry.getValue(); dayForMaxSteps = entry.getKey(); mDB.updateBestSteps(entry.getKey(), entry.getValue()); } } for (IStatsChanged callback : statsCallbackList) { callback.onTotalStepsChanged(totalSteps); callback.onAverageStepsChanged(totalSteps / (arr.size() / 8)); callback.onMaxStepsChanged(dayForMaxSteps, maxSteps); if (valueInStatsChanged.get()) { Log.d(LOG_TAG, "stats values CHANGED"); callback.onLast7DaysStats(stats); } else { Log.d(LOG_TAG, "stats values not changed"); } } } } } }