List of usage examples for com.google.gson JsonPrimitive isBoolean
public boolean isBoolean()
From source file:angularBeans.remote.InvocationHandler.java
License:LGPL
private void update(Object o, JsonObject params) { if (params != null) { // boolean firstIn = false; for (Map.Entry<String, JsonElement> entry : params.entrySet()) { JsonElement value = entry.getValue(); String name = entry.getKey(); if ((name.equals("sessionUID")) || (name.equals("args"))) { continue; }//from ww w . j a v a 2s . co m if ((value.isJsonObject()) && (!value.isJsonNull())) { String getName; try { getName = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name)); Method getter = o.getClass().getMethod(getName); Object subObj = getter.invoke(o); // logger.log(Level.INFO, "#entring sub object "+name); update(subObj, value.getAsJsonObject()); } catch (NoSuchFieldException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException e) { e.printStackTrace(); } } // ------------------------------------ if (value.isJsonArray()) { try { String getter = CommonUtils.obtainGetter(o.getClass().getDeclaredField(name)); Method get = o.getClass().getDeclaredMethod(getter); Type type = get.getGenericReturnType(); ParameterizedType pt = (ParameterizedType) type; Type actType = pt.getActualTypeArguments()[0]; String className = actType.toString(); className = className.substring(className.indexOf("class") + 6); Class clazz = Class.forName(className); JsonArray array = value.getAsJsonArray(); Collection collection = (Collection) get.invoke(o); Object elem; for (JsonElement element : array) { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); elem = element; if (primitive.isBoolean()) elem = primitive.getAsBoolean(); if (primitive.isString()) { elem = primitive.getAsString(); } if (primitive.isNumber()) elem = primitive.isNumber(); } else { elem = util.deserialise(clazz, element); } try { if (collection instanceof List) { if (collection.contains(elem)) collection.remove(elem); } collection.add(elem); } catch (UnsupportedOperationException e) { Logger.getLogger("AngularBeans").log(java.util.logging.Level.WARNING, "trying to modify an immutable collection : " + name); } } } catch (Exception e) { e.printStackTrace(); } } // ------------------------------------------ if (value.isJsonPrimitive() && (!name.equals("setSessionUID"))) { try { if (!CommonUtils.hasSetter(o.getClass(), name)) { continue; } name = "set" + name.substring(0, 1).toUpperCase() + name.substring(1); Class type = null; for (Method set : o.getClass().getDeclaredMethods()) { if (CommonUtils.isSetter(set)) { if (set.getName().equals(name)) { Class<?>[] pType = set.getParameterTypes(); type = pType[0]; break; } } } if (type.equals(LobWrapper.class)) continue; Object param = null; if ((params.entrySet().size() >= 1) && (type != null)) { param = CommonUtils.convertFromString(value.getAsString(), type); } o.getClass().getMethod(name, type).invoke(o, param); } catch (Exception e) { e.printStackTrace(); } } } } }
From source file:at.ac.tuwien.infosys.jcloudscale.datastore.mapping.type.json.JsonBooleanTypeAdapter.java
License:Apache License
@Override public Boolean deserialize(JsonElement element, TypeMetadata<JsonElement> typeMetadata) { JsonPrimitive jsonPrimitive = (JsonPrimitive) element; if (!jsonPrimitive.isBoolean()) { throw new DatastoreException("Invalid value for boolean type."); }// w ww. j av a 2 s. c o m return jsonPrimitive.getAsBoolean(); }
From source file:bind.JsonTreeReader.java
License:Apache License
@Override public JsonToken peek() throws IOException { if (stack.isEmpty()) { return JsonToken.END_DOCUMENT; }/*from w w w . j av a 2s.co m*/ Object o = peekStack(); if (o instanceof Iterator) { Object secondToTop = stack.get(stack.size() - 2); boolean isObject = secondToTop instanceof JsonElement && ((JsonElement) secondToTop).isJsonObject(); Iterator<?> iterator = (Iterator<?>) o; if (iterator.hasNext()) { if (isObject) { return JsonToken.NAME; } else { stack.add(iterator.next()); return peek(); } } else { return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY; } } else if (o instanceof JsonElement) { JsonElement el = (JsonElement) o; if (el.isJsonObject()) { return JsonToken.BEGIN_OBJECT; } else if (el.isJsonArray()) { return JsonToken.BEGIN_ARRAY; } else if (el.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) o; if (primitive.isString()) { return JsonToken.STRING; } else if (primitive.isBoolean()) { return JsonToken.BOOLEAN; } else if (primitive.isNumber()) { return JsonToken.NUMBER; } else { throw new AssertionError(); } } else if (el.isJsonNull()) { return JsonToken.NULL; } throw new AssertionError(); } else if (o == SENTINEL_CLOSED) { throw new IllegalStateException("JsonReader is closed"); } else { throw new AssertionError(); } }
From source file:ccm.pay2spawn.util.JsonNBTHelper.java
License:Open Source License
/** * There is no way to detect number types and NBT is picky about this. Lets hope the original type id is there, otherwise we are royally screwed. *//* ww w . j a v a 2 s . com*/ public static NBTBase parseJSON(JsonPrimitive element) { String string = element.getAsString(); if (string.contains(":")) { for (int id = 0; id < NBTTypes.length; id++) { if (string.startsWith(NBTTypes[id] + ":")) { String value = string.replace(NBTTypes[id] + ":", ""); value = RandomRegistry.solveRandom(id, value); switch (id) { // 0 = END case BYTE: return new NBTTagByte(Byte.parseByte(value)); case SHORT: return new NBTTagShort(Short.parseShort(value)); case INT: return new NBTTagInt(Integer.parseInt(value)); case LONG: return new NBTTagLong(Long.parseLong(value)); case FLOAT: return new NBTTagFloat(Float.parseFloat(value)); case DOUBLE: return new NBTTagDouble(Double.parseDouble(value)); case BYTE_ARRAY: return parseJSONByteArray(value); case STRING: return new NBTTagString(value); // 9 = LIST != JsonPrimitive // 10 = COMPOUND != JsonPrimitive case INT_ARRAY: return parseJSONIntArray(value); } } } } // Now it becomes guesswork. if (element.isString()) return new NBTTagString(string); if (element.isBoolean()) return new NBTTagByte((byte) (element.getAsBoolean() ? 1 : 0)); Number n = element.getAsNumber(); if (n instanceof Byte) return new NBTTagByte(n.byteValue()); if (n instanceof Short) return new NBTTagShort(n.shortValue()); if (n instanceof Integer) return new NBTTagInt(n.intValue()); if (n instanceof Long) return new NBTTagLong(n.longValue()); if (n instanceof Float) return new NBTTagFloat(n.floatValue()); if (n instanceof Double) return new NBTTagDouble(n.doubleValue()); throw new NumberFormatException(element.toString() + " is was not able to be parsed."); }
From source file:ccm.pay2spawn.util.JsonNBTHelper.java
License:Open Source License
public static JsonPrimitive fixNulls(JsonPrimitive primitive) { if (primitive.isBoolean()) return new JsonPrimitive(primitive.getAsBoolean()); if (primitive.isNumber()) return new JsonPrimitive(primitive.getAsNumber()); if (primitive.isString()) return new JsonPrimitive(primitive.getAsString()); return JSON_PARSER.parse(primitive.toString()).getAsJsonPrimitive(); }
From source file:ch.cern.db.flume.sink.elasticsearch.serializer.JSONtoElasticSearchEventSerializer.java
License:GNU General Public License
private void appendBody(XContentBuilder builder, Event event) throws IOException { JsonParser parser = new JsonParser(); JsonObject json = parser.parse(new String(event.getBody())).getAsJsonObject(); for (Entry<String, JsonElement> property : json.entrySet()) { if (property.getValue().isJsonNull()) { builder.nullField(property.getKey()); continue; }//from ww w.j a v a2s .co m if (!property.getValue().isJsonPrimitive()) { builder.field(property.getKey(), property.getValue()); continue; } JsonPrimitive primitiveValue = (JsonPrimitive) property.getValue(); if (primitiveValue.isBoolean()) builder.field(property.getKey(), primitiveValue.getAsBoolean()); else if (primitiveValue.isNumber()) if (primitiveValue.getAsString().indexOf('.') != -1) builder.field(property.getKey(), primitiveValue.getAsNumber().doubleValue()); else builder.field(property.getKey(), primitiveValue.getAsNumber().longValue()); else if (primitiveValue.isString()) builder.field(property.getKey(), primitiveValue.getAsString()); } }
From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java
License:Apache License
/** * Set generic array property for a resource, based on an array found in the retrieved JSON. * * @param jsonArray JsonArray//from ww w. j av a2s. c o m * @param key String * @param resource Resource * @throws RepositoryException exception */ private void setNodeSimpleArrayProperty(final JsonArray jsonArray, final String key, final Resource resource) throws RepositoryException { JsonPrimitive firstVal = jsonArray.get(0).getAsJsonPrimitive(); try { Object[] values; if (firstVal.isBoolean()) { values = new Boolean[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsBoolean(); } } else if (DECIMAL_REGEX.matcher(firstVal.getAsString()).matches()) { values = new BigDecimal[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsBigDecimal(); } } else if (firstVal.isNumber()) { values = new Long[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsLong(); } } else { values = new String[jsonArray.size()]; for (int i = 0; i < jsonArray.size(); i++) { values[i] = jsonArray.get(i).getAsString(); } } ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class); resourceProperties.put(key, values); LOG.trace("Array property '{}' added for resource '{}'", key, resource.getPath()); } catch (Exception e) { LOG.error("Unable to assign property '{}' to resource '{}'", key, resource.getPath(), e); } }
From source file:com.adobe.acs.commons.remoteassets.impl.RemoteAssetsNodeSyncImpl.java
License:Apache License
/** * Set a simple resource property from the fetched JSON. * * @param value Object//w w w .j av a 2 s. c om * @param key String * @param resource Resource * @throws RepositoryException exception */ private void setNodeSimpleProperty(final JsonPrimitive value, final String key, final Resource resource) throws RepositoryException { ValueMap resourceProperties = resource.adaptTo(ModifiableValueMap.class); if (value.isString() && DATE_REGEX.matcher(value.getAsString()).matches()) { try { resourceProperties.put(key, GregorianCalendar.from(ZonedDateTime.parse(value.getAsString(), DATE_TIME_FORMATTER))); } catch (DateTimeParseException e) { LOG.warn("Unable to parse date '{}' for property:resource '{}'.", value, key + ":" + resource.getPath()); } } else if (value.isString() && DECIMAL_REGEX.matcher(value.getAsString()).matches()) { resourceProperties.put(key, value.getAsBigDecimal()); } else if (value.isBoolean()) { resourceProperties.put(key, value.getAsBoolean()); } else if (value.isNumber()) { if (DECIMAL_REGEX.matcher(value.getAsString()).matches()) { resourceProperties.put(key, value.getAsBigDecimal()); } else { resourceProperties.put(key, value.getAsLong()); } } else if (value.isJsonNull()) { resourceProperties.remove(key); } else { resourceProperties.put(key, value.getAsString()); } LOG.trace("Property '{}' added for resource '{}'.", key, resource.getPath()); }
From source file:com.balajeetm.mystique.core.module.GsonSerialiser.java
License:Open Source License
@Override public void serialize(JsonElement value, JsonGenerator gen, SerializerProvider provider) throws IOException { if (jsonLever.isNull(value)) { gen.writeNull();//w ww . j av a 2 s .c o m } else if (jsonLever.isObject(value)) { gen.writeStartObject(); JsonObject jsonObject = value.getAsJsonObject(); for (Entry<String, JsonElement> entry : jsonObject.entrySet()) { gen.writeFieldName(entry.getKey()); serialize(entry.getValue(), gen, provider); } gen.writeEndObject(); } else if (jsonLever.isArray(value)) { gen.writeStartArray(); JsonArray jsonArray = value.getAsJsonArray(); for (JsonElement jsonElement : jsonArray) { serialize(jsonElement, gen, provider); } gen.writeEndArray(); } else if (jsonLever.isPrimitive(value)) { JsonPrimitive jsonPrimitive = value.getAsJsonPrimitive(); if (jsonPrimitive.isBoolean()) { gen.writeBoolean(jsonPrimitive.getAsBoolean()); } if (jsonPrimitive.isNumber()) { Number nnode = jsonPrimitive.getAsNumber(); if (nnode instanceof LazilyParsedNumber) { gen.writeNumber(nnode.toString()); } else if (nnode instanceof Integer) { gen.writeNumber(nnode.intValue()); } else if (nnode instanceof Short) { gen.writeNumber(nnode.shortValue()); } else if (nnode instanceof BigInteger || nnode instanceof Long) { gen.writeNumber(nnode.longValue()); } else if (nnode instanceof Float) { gen.writeNumber(nnode.floatValue()); } else if (nnode instanceof Double || nnode instanceof BigDecimal) { gen.writeNumber(nnode.doubleValue()); } } if (jsonPrimitive.isString()) { gen.writeString(jsonPrimitive.getAsString()); } } }
From source file:com.bzcentre.dapiPush.MeetingPayload.java
License:Open Source License
private Object extractAps(JsonElement in) { if (in == null || in.isJsonNull()) return null; if (in.isJsonArray()) { List<Object> list = new ArrayList<>(); JsonArray arr = in.getAsJsonArray(); for (JsonElement anArr : arr) { list.add(extractAps(anArr)); }/* ww w . jav a 2s . c o m*/ return list; } else if (in.isJsonObject()) { Map<String, Object> map = new LinkedTreeMap<>(); JsonObject obj = in.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet(); for (Map.Entry<String, JsonElement> entry : entitySet) { map.put(entry.getKey(), extractAps(entry.getValue())); NginxClojureRT.log.debug(TAG + entry.getKey() + "=>" + map.get(entry.getKey()) + "=>" + map.get(entry.getKey()).getClass().getTypeName()); switch (entry.getKey()) { case "dapi": this.setDapi(map.get(entry.getKey())); break; case "acme1": this.setAcme1(map.get(entry.getKey())); break; case "acme2": this.setAcme2(map.get(entry.getKey())); break; case "acme3": this.setAcme3(map.get(entry.getKey())); break; case "acme4": this.setAcme4(map.get(entry.getKey())); break; case "acme5": this.setAcme5(map.get(entry.getKey())); break; case "acme6": this.setAcme6(map.get(entry.getKey())); break; case "acme7": this.setAcme7(map.get(entry.getKey())); break; case "acme8": this.setAcme8(map.get(entry.getKey())); break; case "aps": NginxClojureRT.log.debug(TAG + "aps initialized"); break; case "badge": this.getAps().setBadge(map.get(entry.getKey())); break; case "sound": this.getAps().setSound(map.get(entry.getKey())); break; case "alert": NginxClojureRT.log.debug(TAG + "alert initialized"); break; case "title": this.getAps().getAlert().setTitle(map.get(entry.getKey())); break; case "body": this.getAps().getAlert().setBody(map.get(entry.getKey())); break; case "action-loc-key": this.getAps().getAlert().setActionLocKey(map.get(entry.getKey())); break; default: NginxClojureRT.log.info(TAG + "Unhandled field : " + entry.getKey()); break; } } return map; } else if (in.isJsonPrimitive()) { JsonPrimitive prim = in.getAsJsonPrimitive(); if (prim.isBoolean()) { return prim.getAsBoolean(); } else if (prim.isString()) { return prim.getAsString(); } else if (prim.isNumber()) { Number num = prim.getAsNumber(); // here you can handle double int/long values // and return any type you want // this solution will transform 3.0 float to long values if (Math.ceil(num.doubleValue()) == num.longValue()) { return num.longValue(); } else { return num.doubleValue(); } } } NginxClojureRT.log.info("Handling json null"); return null; }