List of usage examples for com.google.gson JsonElement isJsonArray
public boolean isJsonArray()
From source file:cpw.mods.fml.common.MetadataCollection.java
License:Open Source License
public static MetadataCollection from(InputStream inputStream, String sourceName) { if (inputStream == null) { return new MetadataCollection(); }/*from w ww .j a va2 s . c o m*/ InputStreamReader reader = new InputStreamReader(inputStream); try { MetadataCollection collection; Gson gson = new GsonBuilder().registerTypeAdapter(ArtifactVersion.class, new ArtifactVersionAdapter()) .create(); JsonParser parser = new JsonParser(); JsonElement rootElement = parser.parse(reader); if (rootElement.isJsonArray()) { collection = new MetadataCollection(); JsonArray jsonList = rootElement.getAsJsonArray(); collection.modList = new ModMetadata[jsonList.size()]; int i = 0; for (JsonElement mod : jsonList) { collection.modList[i++] = gson.fromJson(mod, ModMetadata.class); } } else { collection = gson.fromJson(rootElement, MetadataCollection.class); } collection.parseModMetadataList(); return collection; } catch (JsonParseException e) { FMLLog.log(Level.ERROR, e, "The mcmod.info file in %s cannot be parsed as valid JSON. It will be ignored", sourceName); return new MetadataCollection(); } catch (Exception e) { throw Throwables.propagate(e); } }
From source file:DAO.ValidationDAO.ValidationOperationSource.java
public boolean jsonCompare(JsonElement element1, JsonElement element2) { //-------------------Caso o Json seja NULO------------------------------ if (element1.isJsonNull()) { //System.out.println("Element is null"); //---------------Caso o Json seja uma primitiva------------------------- } else if (element1.isJsonPrimitive()) { //System.out.println("Element is primitive"); //----------------Caso o Json seja um Objeto---------------------------- } else if (element1.isJsonObject()) { //System.out.println("Element is object"); Iterator<Map.Entry<String, JsonElement>> CrunchifyIterator = element1.getAsJsonObject().entrySet() .iterator();/* w w w . j a v a 2 s . co m*/ while (CrunchifyIterator.hasNext()) { Map.Entry<String, JsonElement> aux = CrunchifyIterator.next(); //System.out.println("Field:" + aux.getKey()); if (findElement(element2, aux.getKey()) == false) { //System.out.println("NOT FOUND Field:" + aux.getKey()); return false; } else if (findElement(element2, aux.getKey()) == true) { //System.out.println("FOUND Field:" + aux.getKey()); if (jsonCompare(aux.getValue(), element2) == false) { return false; } } } //------------Caso o json seja um array--------------------------------- } else if (element1.isJsonArray()) { //System.out.println("Element is array"); for (JsonElement jsonElement : element1.getAsJsonArray()) { if (jsonCompare(jsonElement, element2) == false) { return false; } } } return true; }
From source file:DAO.ValidationDAO.ValidationOperationSource.java
public boolean findElement(JsonElement element, String field) { //-------------------Caso o Json seja NULO------------------------------ if (element.isJsonNull()) { //System.out.println("Element is null"); //---------------Caso o Json seja uma primitiva------------------------- } else if (element.isJsonPrimitive()) { //System.out.println("Element is primitive"); //----------------Caso o Json seja um Objeto---------------------------- } else if (element.isJsonObject()) { //System.out.println("Element is object"); if (element.getAsJsonObject().has(field)) { //System.out.println("Object found --> " + element.getAsJsonObject().get(field).toString()); return true; } else {//from ww w.j av a2s . c o m Iterator<Map.Entry<String, JsonElement>> CrunchifyIterator = element.getAsJsonObject().entrySet() .iterator(); while (CrunchifyIterator.hasNext()) { if (findElement(CrunchifyIterator.next().getValue(), field) == true) { return true; } } } //------------Caso o json seja um array--------------------------------- } else if (element.isJsonArray()) { //System.out.println("Element is array"); for (JsonElement jsonElement : element.getAsJsonArray()) { if (findElement(jsonElement, field) == true) { return true; } } } return false; }
From source file:DAO.ValidationDAO.ValidationOperationSource.java
public boolean findElementAndValue(JsonElement element, String field, String value) { //-------------------Caso o Json seja NULO------------------------------ if (element.isJsonNull()) { //System.out.println("Element is null"); //---------------Caso o Json seja uma primitiva------------------------- } else if (element.isJsonPrimitive()) { //System.out.println("Element is primitive"); //----------------Caso o Json seja um Objeto---------------------------- } else if (element.isJsonObject()) { //System.out.println("Element is object"); if (element.getAsJsonObject().has(field) && element.getAsJsonObject().get(field).toString().contains(value)) { //System.out.println("Object found --> " + element.getAsJsonObject().get(field).toString()); return true; } else {/*from w w w.j av a 2s . c o m*/ Iterator<Map.Entry<String, JsonElement>> CrunchifyIterator = element.getAsJsonObject().entrySet() .iterator(); while (CrunchifyIterator.hasNext()) { if (findElementAndValue(CrunchifyIterator.next().getValue(), field, value) == true) { return true; } } } //------------Caso o json seja um array--------------------------------- } else if (element.isJsonArray()) { //System.out.println("Element is array"); for (JsonElement jsonElement : element.getAsJsonArray()) { if (findElementAndValue(jsonElement, field, value) == true) { return true; } } } return false; }
From source file:Days.Day12.java
public int parseElement(JsonElement element) { int totaal = 0; if (element.isJsonArray()) { totaal += parseArray(element.getAsJsonArray()); } else if (element.isJsonObject()) { totaal += parseObject(element.getAsJsonObject()); } else if (element.isJsonPrimitive()) { totaal += parsePrimitive(element.getAsJsonPrimitive()); }/*from w ww . java 2 s.c o m*/ return totaal; }
From source file:de.arkraft.jenkins.JenkinsHelper.java
License:Apache License
public static GsonBuilder getGsonBuilder() { GsonBuilder builder = new GsonBuilder(); builder.registerTypeAdapter(DateTime.class, new JsonDeserializer<DateTime>() { @Override// w ww . j a va 2s . c o m public DateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { // using the correct parser right away should save init time compared to new DateTime(<string>) return ISO_8601_WITH_MILLIS.parseDateTime(json.getAsString()); } }); builder.registerTypeAdapter(DateTime.class, new JsonSerializer<DateTime>() { @Override public JsonElement serialize(DateTime src, Type typeOfSrc, JsonSerializationContext context) { return new JsonPrimitive(src.toString()); } }); builder.registerTypeAdapter(Duration.class, new JsonDeserializer() { @Override public Object deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return Duration.parse("PT" + json.getAsString() + "S"); } }); builder.registerTypeAdapter(Action.class, new JsonDeserializer<Action>() { @Override public Action deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { JsonObject object = ((JsonObject) jsonElement); if (object.has("causes")) { JsonElement element = object.get("causes"); if (element.isJsonArray()) { return jsonDeserializationContext.deserialize(element, Causes.class); } } if (object.has("failCount")) { return jsonDeserializationContext.deserialize(object, CountAction.class); } return null; } }); builder.registerTypeAdapter(ChangeSet.class, new JsonDeserializer<ChangeSet>() { @Override public ChangeSet deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { ChangeSet changeSet = new ChangeSet(); JsonObject object = (JsonObject) jsonElement; if (object.has("items") && object.get("items").isJsonArray()) { for (JsonElement element : object.get("items").getAsJsonArray()) { ChangeSet.Change change = context.deserialize(element, ChangeSet.Change.class); changeSet.add(change); } } if (object.has("kind")) { changeSet.setKind(object.get("kind").getAsString()); } return changeSet; } }); builder.registerTypeAdapter(Duration.class, new JsonSerializer<Duration>() { @Override public JsonElement serialize(Duration duration, Type type, JsonSerializationContext jsonSerializationContext) { return new JsonPrimitive(duration.toString().replace("PT", "").replace("S", "")); } }); builder.registerTypeAdapter(EditType.class, new JsonDeserializer<EditType>() { @Override public EditType deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return EditType.byName(jsonElement.getAsString()); } }); builder.registerTypeAdapter(HealthIcon.class, new JsonDeserializer<HealthIcon>() { @Override public HealthIcon deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { return HealthIcon.fromName(jsonElement.toString()); } }); builder.registerTypeAdapter(Queue.class, new JsonDeserializer<Queue>() { @Override public Queue deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext context) throws JsonParseException { Queue queue = new Queue(); JsonObject jsonObject = (JsonObject) jsonElement; if (jsonObject.has("items") && jsonObject.get("items").isJsonArray()) { for (JsonElement element : jsonObject.get("items").getAsJsonArray()) { Queue.Item build = context.deserialize(element, Queue.Item.class); queue.add(build); } } return queue; } }); builder.registerTypeAdapter(JobCollection.class, new JsonDeserializer<JobCollection>() { @Override public JobCollection deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { JobCollection jobs = new JobCollection(); JsonObject object = (JsonObject) json; if (object.has("jobs") && object.get("jobs").isJsonArray()) { for (JsonElement element : object.get("jobs").getAsJsonArray()) { Job job = context.deserialize(element, Job.class); jobs.add(job); } } return jobs; } }); builder.registerTypeAdapter(BallColor.class, new JsonDeserializer<BallColor>() { @Override public BallColor deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext json) throws JsonParseException { return BallColor.valueOf(jsonElement.getAsString().toUpperCase()); } }); return builder; }
From source file:de.azapps.mirakel.model.list.SpecialListsWhereDeserializer.java
License:Open Source License
@NonNull private static Optional<SpecialListsBaseProperty> parseSpecialListWhere(final @NonNull JsonElement obj, final int deep) throws IllegalArgumentException { if (obj.isJsonObject()) { return parseSpecialListsCondition(obj); } else if (obj.isJsonArray()) { final List<SpecialListsBaseProperty> childs = new ArrayList<>(obj.getAsJsonArray().size()); for (final JsonElement el : obj.getAsJsonArray()) { final Optional<SpecialListsBaseProperty> child = parseSpecialListWhere(el, deep + 1); if (child.isPresent()) { childs.add(child.get()); }//from w w w. j ava 2 s . co m } return of((SpecialListsBaseProperty) new SpecialListsConjunctionList( ((deep % 2) == 0) ? SpecialListsConjunctionList.CONJUNCTION.AND : SpecialListsConjunctionList.CONJUNCTION.OR, childs)); } else if (obj.isJsonNull()) { return absent(); } else { throw new IllegalArgumentException("Unknown json type"); } }
From source file:de.azapps.mirakel.model.task.TaskDeserializer.java
License:Open Source License
private static void handleAdditionalEntries(final Task t, final String key, final JsonElement val) { if (val.isJsonPrimitive()) { final JsonPrimitive p = (JsonPrimitive) val; if (p.isBoolean()) { t.addAdditionalEntry(key, String.valueOf(val.getAsBoolean())); } else if (p.isNumber()) { t.addAdditionalEntry(key, String.valueOf(val.getAsInt())); } else if (p.isJsonNull()) { t.addAdditionalEntry(key, "null"); } else if (p.isString()) { t.addAdditionalEntry(key, '"' + val.getAsString() + '"'); } else {// www . j a v a 2 s. com Log.w(TAG, "unknown json-type"); } } else if (val.isJsonArray()) { final JsonArray a = (JsonArray) val; StringBuilder s = new StringBuilder("["); boolean first = true; for (final JsonElement e : a) { if (e.isJsonPrimitive()) { final JsonPrimitive p = (JsonPrimitive) e; final String add; if (p.isBoolean()) { add = String.valueOf(p.getAsBoolean()); } else if (p.isNumber()) { add = String.valueOf(p.getAsInt()); } else if (p.isString()) { add = '"' + p.getAsString() + '"'; } else if (p.isJsonNull()) { add = "null"; } else { Log.w(TAG, "unknown json-type"); break; } s.append(first ? "" : ",").append(add); first = false; } else { Log.w(TAG, "unknown json-type"); } } t.addAdditionalEntry(key, s + "]"); } else { Log.w(TAG, "unknown json-type"); } }
From source file:de.dfki.mmf.attributeselection.AttributeSelectionAlgorithm.java
License:Open Source License
/** * @return list with JsonObjects each containing those attributes of the queried object which discriminates it from the compared database object *///from www . ja v a 2 s . c om public List<JsonObject> computeSingleDiscriminatingIdentifiers() { //data structure to save discriminating identifiers resulting from the comparisons between queried object and each database object ArrayList<JsonObject> identifiers = new ArrayList<>(); for (JsonObject databaseObject : databaseObjects) { //create list for each comparison of queried object properties and the properties of a database object // to save property values which uniquely identify queried object JsonObject singleDiscriminatingIdentifiers = new JsonObject(); //go over each property of the queried object Set<Map.Entry<String, JsonElement>> entrySet = queriedObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entrySet) { String queryKey = entry.getKey(); //check saliencyAnnotation is exists if (saliencyAnnotations != null) { //look up the saliency annotation of the object if (saliencyAnnotations.has(queryKey)) { double saliencyNbr = saliencyAnnotations.get(queryKey).getAsDouble(); //if saliency is lower than threshold -> property will be pruned, continue with next property if (saliencyNbr < saliencyThreshold) { continue; } } else { continue; } } //the values the queried object has for certain property JsonElement queriedPropertyValues = queriedObject.get(queryKey); //check if database object has this property if (databaseObject.has(queryKey)) { //get the values the database object has for this property JsonElement dataPropertyValues = databaseObject.get(queryKey); //check if objects have the same values for this property -> if not add values of queried object to list if ((queriedPropertyValues.isJsonArray() && !dataPropertyValues.isJsonArray()) || (!queriedPropertyValues.isJsonArray() && dataPropertyValues.isJsonArray())) { singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues); } else if (!queriedPropertyValues.isJsonArray() && !dataPropertyValues.isJsonArray()) { if (!Objects.equals(queriedPropertyValues.toString(), dataPropertyValues.toString())) { singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues); } } else if (queriedPropertyValues.isJsonArray() && dataPropertyValues.isJsonArray()) { JsonArray queryArray = queriedPropertyValues.getAsJsonArray(); JsonArray dataArray = dataPropertyValues.getAsJsonArray(); boolean added = false; for (JsonElement queryElement : queryArray) { if (!dataArray.contains(queryElement)) { singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues); added = true; break; } } if (!added) { for (JsonElement dataElement : dataArray) { if (!queryArray.contains(dataElement)) { singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues); break; } } } } //compared database object does not have particular property -> can be seen as differentiating } else { singleDiscriminatingIdentifiers.add(queryKey, queriedPropertyValues); } } //add single discriminating identifiers to list with all found identifiers identifiers.add(singleDiscriminatingIdentifiers); } return identifiers; }
From source file:de.fabianonline.telegram_backup.Utils.java
License:Open Source License
static Version getNewestVersion() { try {/*from w w w . ja va 2s.co m*/ String data_url = "https://api.github.com/repos/fabianonline/telegram_backup/releases"; logger.debug("Requesting current release info from {}", data_url); String json = IOUtils.toString(new URL(data_url)); JsonParser parser = new JsonParser(); JsonElement root_elm = parser.parse(json); if (root_elm.isJsonArray()) { JsonArray root = root_elm.getAsJsonArray(); JsonObject newest_version = null; for (JsonElement e : root) if (e.isJsonObject()) { JsonObject version = e.getAsJsonObject(); if (version.getAsJsonPrimitive("prerelease").getAsBoolean() == false) { newest_version = version; break; } } if (newest_version == null) return null; String new_v = newest_version.getAsJsonPrimitive("tag_name").getAsString(); logger.debug("Found current release version {}", new_v); String cur_v = Config.APP_APPVER; int result = compareVersions(cur_v, new_v); return new Version(new_v, newest_version.getAsJsonPrimitive("html_url").getAsString(), newest_version.getAsJsonPrimitive("body").getAsString(), result == VERSION_2_NEWER); } return null; } catch (Exception e) { return null; } }