List of usage examples for com.google.gson JsonPrimitive getAsNumber
@Override
public Number getAsNumber()
From source file:org.apache.hadoop.hive.json.JsonShredder.java
License:Apache License
private void shredObject(String name, JsonElement json) throws IOException { if (json.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) json; if (primitive.isBoolean()) { getFile(name).append(primitive.getAsBoolean() + "\n"); } else if (primitive.isString()) { getFile(name).append(primitive.getAsString().replace("\\", "\\\\").replace("\n", "\\n") + "\n"); } else if (primitive.isNumber()) { getFile(name).append(primitive.getAsNumber() + "\n"); }/*from www . j a v a2 s .co m*/ } else if (json.isJsonNull()) { // just skip it } else if (json.isJsonArray()) { for (JsonElement child : ((JsonArray) json)) { shredObject(name, child); } } else { JsonObject obj = (JsonObject) json; for (Map.Entry<String, JsonElement> field : obj.entrySet()) { String fieldName = field.getKey(); shredObject(name + "." + fieldName, field.getValue()); } } }
From source file:org.devnexus.aerogear.ShadowStore.java
License:Apache License
private void saveElement(JsonObject serialized, String path, Serializable id) { String sql = String.format( "insert into shadow_%s_property (PROPERTY_NAME, PROPERTY_VALUE, PARENT_ID) values (?,?,?)", className);/*from ww w.j ava 2 s.c om*/ Set<Map.Entry<String, JsonElement>> members = serialized.entrySet(); String pathVar = path.isEmpty() ? "" : "."; for (Map.Entry<String, JsonElement> member : members) { JsonElement jsonValue = member.getValue(); String propertyName = member.getKey(); if (jsonValue.isJsonObject()) { saveElement((JsonObject) jsonValue, path + pathVar + propertyName, id); } else if (jsonValue.isJsonArray()) { JsonArray jsonArray = jsonValue.getAsJsonArray(); for (int index = 0; index < jsonArray.size(); index++) { JsonElement arrayElement = jsonArray.get(index); if (arrayElement.isJsonPrimitive()) { JsonPrimitive primitive = arrayElement.getAsJsonPrimitive(); if (primitive.isBoolean()) { String value = primitive.getAsBoolean() ? "true" : "false"; getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName + String.format("[%d]", index), value, id }); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName + String.format("[%d]", index), value, id }); } else if (primitive.isString()) { String value = primitive.getAsString(); getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName + String.format("[%d]", index), value, id }); } else { throw new IllegalArgumentException( arrayElement + " isn't a number, boolean, or string"); } } else { saveElement(arrayElement.getAsJsonObject(), path + pathVar + propertyName + String.format("[%d]", index), id); } } } else { if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { String value = primitive.getAsBoolean() ? "true" : "false"; getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id }); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id }); } else if (primitive.isString()) { String value = primitive.getAsString(); getDatabase().execSQL(sql, new Object[] { path + pathVar + propertyName, value, id }); } else { throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string"); } } else { throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive"); } } } }
From source file:org.devnexus.aerogear.ShadowStore.java
License:Apache License
private void buildKeyValuePairs(JsonObject where, List<Pair<String, String>> keyValues, String parentPath) { Set<Map.Entry<String, JsonElement>> keys = where.entrySet(); String pathVar = parentPath.isEmpty() ? "" : ".";//Set a dot if parent path is not empty for (Map.Entry<String, JsonElement> entry : keys) { String key = entry.getKey(); String path = parentPath + pathVar + key; JsonElement jsonValue = entry.getValue(); if (jsonValue.isJsonObject()) { buildKeyValuePairs((JsonObject) jsonValue, keyValues, path); } else {//from ww w .ja va2 s . c om if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { String value = primitive.getAsBoolean() ? "true" : "false"; keyValues.add(new Pair<String, String>(path, value)); } else if (primitive.isNumber()) { Number value = primitive.getAsNumber(); keyValues.add(new Pair<String, String>(path, value.toString())); } else if (primitive.isString()) { String value = primitive.getAsString(); keyValues.add(new Pair<String, String>(path, value)); } else { throw new IllegalArgumentException(jsonValue + " isn't a number, boolean, or string"); } } else { throw new IllegalArgumentException(jsonValue + " isn't a JsonPrimitive"); } } } }
From source file:org.eclipse.leshan.standalone.servlet.json.LwM2mNodeDeserializer.java
License:Open Source License
private Value<?> deserializeValue(JsonPrimitive val) { Value<?> value = null;/*from ww w . j ava 2 s . c o m*/ if (val.isNumber()) { Number n = val.getAsNumber(); if (n.doubleValue() == (long) n.doubleValue()) { Long lValue = Long.valueOf(n.longValue()); if (lValue >= Integer.MIN_VALUE && lValue <= Integer.MAX_VALUE) { value = Value.newIntegerValue(lValue.intValue()); } else { value = Value.newLongValue(lValue); } } else { Double dValue = Double.valueOf(n.doubleValue()); if (dValue >= Float.MIN_VALUE && dValue <= Float.MAX_VALUE) { value = Value.newFloatValue(dValue.floatValue()); } else { value = Value.newDoubleValue(dValue); } } } else if (val.isBoolean()) { value = Value.newBooleanValue(val.getAsBoolean()); } else if (val.isString()) { value = Value.newStringValue(val.getAsString()); } return value; }
From source file:org.eclipse.milo.opcua.binaryschema.gson.JsonStructureCodec.java
License:Open Source License
@Override protected Object memberTypeToOpcUaScalar(JsonElement member, String typeName) { if (member == null || member.isJsonNull()) { return null; } else if (member.isJsonArray()) { JsonArray array = member.getAsJsonArray(); switch (typeName) { case "ByteString": { byte[] bs = new byte[array.size()]; for (int i = 0; i < array.size(); i++) { bs[i] = array.get(i).getAsByte(); }//from www . ja va 2 s . c om return ByteString.of(bs); } default: return array; } } else if (member.isJsonObject()) { JsonObject jsonObject = member.getAsJsonObject(); switch (typeName) { case "QualifiedName": { return new QualifiedName(jsonObject.get("namespaceIndex").getAsInt(), jsonObject.get("name").getAsString()); } case "LocalizedText": { return new LocalizedText(jsonObject.get("locale").getAsString(), jsonObject.get("text").getAsString()); } default: return jsonObject; } } else if (member.isJsonPrimitive()) { JsonPrimitive primitive = member.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isString()) { switch (typeName) { case "Guid": return UUID.fromString(primitive.getAsString()); case "NodeId": return NodeId.parseSafe(primitive.getAsString()).orElse(NodeId.NULL_VALUE); case "ExpandedNodeId": return ExpandedNodeId.parse(primitive.getAsString()); case "XmlElement": return new XmlElement(primitive.getAsString()); default: return primitive.getAsString(); } } else if (primitive.isNumber()) { switch (typeName) { case "SByte": return primitive.getAsByte(); case "Int16": return primitive.getAsShort(); case "Int32": return primitive.getAsInt(); case "Int64": return primitive.getAsLong(); case "Byte": return ubyte(primitive.getAsShort()); case "UInt16": return ushort(primitive.getAsInt()); case "UInt32": return uint(primitive.getAsLong()); case "UInt64": return ulong(primitive.getAsBigInteger()); case "Float": return primitive.getAsFloat(); case "Double": return primitive.getAsDouble(); case "DateTime": return new DateTime(primitive.getAsLong()); case "StatusCode": return new StatusCode(primitive.getAsLong()); default: return primitive.getAsNumber(); } } } return null; }
From source file:org.eclipse.scada.base.json.VariantJsonDeserializer.java
License:Open Source License
private Variant decodeFromPrimitive(final JsonElement json) { final JsonPrimitive jsonPrim = (JsonPrimitive) json; if (jsonPrim.isBoolean()) { return Variant.valueOf(jsonPrim.getAsBoolean()); } else if (jsonPrim.isNumber()) { return Variant.valueOf(jsonPrim.getAsNumber()); } else {//w w w. j av a 2s . co m return VariantEditor.toVariant(jsonPrim.getAsString()); } }
From source file:org.geogit.rest.repository.MergeFeatureResource.java
License:Open Source License
public void post(Representation entity) { InputStream input = null;//from w w w . j av a2 s. co m try { input = getRequest().getEntity().getStream(); final GeoGIT ggit = getGeogit(getRequest()).get(); final Reader body = new InputStreamReader(input); final JsonParser parser = new JsonParser(); final JsonElement conflictJson = parser.parse(body); if (conflictJson.isJsonObject()) { final JsonObject conflict = conflictJson.getAsJsonObject(); String featureId = null; RevFeature ourFeature = null; RevFeatureType ourFeatureType = null; RevFeature theirFeature = null; RevFeatureType theirFeatureType = null; JsonObject merges = null; if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) { featureId = conflict.get("path").getAsJsonPrimitive().getAsString(); } Preconditions.checkState(featureId != null); if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) { String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString(); Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit); if (ourNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(ourNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); ourFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class).setObjectId(ourNode.get().getMetadataId()) .call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); ourFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) { String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString(); Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit); if (theirNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(theirNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); theirFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class).setObjectId(theirNode.get().getMetadataId()) .call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); theirFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("merges") && conflict.get("merges").isJsonObject()) { merges = conflict.get("merges").getAsJsonObject(); } Preconditions.checkState(merges != null); Preconditions.checkState(ourFeatureType != null || theirFeatureType != null); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type())); ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType : ourFeatureType).sortedDescriptors(); for (Entry<String, JsonElement> entry : merges.entrySet()) { int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors); if (descriptorIndex != -1 && entry.getValue().isJsonObject()) { PropertyDescriptor descriptor = descriptors.get(descriptorIndex); JsonObject attributeObject = entry.getValue().getAsJsonObject(); if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive() && attributeObject.get("ours").getAsBoolean()) { featureBuilder.set(descriptor.getName(), ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive() && attributeObject.get("theirs").getAsBoolean()) { featureBuilder.set(descriptor.getName(), theirFeature == null ? null : theirFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) { JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive(); if (primitive.isString()) { try { Object object = valueFromString( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsString()); featureBuilder.set(descriptor.getName(), object); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isNumber()) { try { Object value = valueFromNumber( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsNumber()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isBoolean()) { try { Object value = valueFromBoolean( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsBoolean()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isJsonNull()) { featureBuilder.set(descriptor.getName(), null); } else { throw new Exception( "Unsupported JSON type for attribute value (" + entry.getKey() + ")"); } } } } SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId)); RevFeature revFeature = RevFeatureBuilder.build(feature); ggit.getRepository().stagingDatabase().put(revFeature); getResponse() .setEntity(new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN)); } } catch (Exception e) { throw new RestletException(e.getMessage(), Status.SERVER_ERROR_INTERNAL, e); } finally { if (input != null) Closeables.closeQuietly(input); } }
From source file:org.geogit.web.api.repo.MergeFeatureResource.java
License:Open Source License
@Override protected Representation post(Representation entity) throws ResourceException { try {//from w ww . j av a 2 s . c om final GeoGIT ggit = (GeoGIT) getApplication().getContext().getAttributes().get("geogit"); final Reader body = entity.getReader(); final JsonParser parser = new JsonParser(); final JsonElement conflictJson = parser.parse(body); Preconditions.checkArgument(conflictJson.isJsonObject(), "Post data should be a JSON Object."); final JsonObject conflict = conflictJson.getAsJsonObject(); String featureId = null; RevFeature ourFeature = null; RevFeatureType ourFeatureType = null; RevFeature theirFeature = null; RevFeatureType theirFeatureType = null; JsonObject merges = null; if (conflict.has("path") && conflict.get("path").isJsonPrimitive()) { featureId = conflict.get("path").getAsJsonPrimitive().getAsString(); } Preconditions.checkState(featureId != null); if (conflict.has("ours") && conflict.get("ours").isJsonPrimitive()) { String ourCommit = conflict.get("ours").getAsJsonPrimitive().getAsString(); Optional<NodeRef> ourNode = parseID(ObjectId.valueOf(ourCommit), featureId, ggit); if (ourNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(ourNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); ourFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class).setObjectId(ourNode.get().getMetadataId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); ourFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("theirs") && conflict.get("theirs").isJsonPrimitive()) { String theirCommit = conflict.get("theirs").getAsJsonPrimitive().getAsString(); Optional<NodeRef> theirNode = parseID(ObjectId.valueOf(theirCommit), featureId, ggit); if (theirNode.isPresent()) { Optional<RevObject> object = ggit.command(RevObjectParse.class) .setObjectId(theirNode.get().objectId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeature); theirFeature = (RevFeature) object.get(); object = ggit.command(RevObjectParse.class).setObjectId(theirNode.get().getMetadataId()).call(); Preconditions.checkState(object.isPresent() && object.get() instanceof RevFeatureType); theirFeatureType = (RevFeatureType) object.get(); } } if (conflict.has("merges") && conflict.get("merges").isJsonObject()) { merges = conflict.get("merges").getAsJsonObject(); } Preconditions.checkState(merges != null); Preconditions.checkState(ourFeatureType != null || theirFeatureType != null); SimpleFeatureBuilder featureBuilder = new SimpleFeatureBuilder( (SimpleFeatureType) (ourFeatureType != null ? ourFeatureType.type() : theirFeatureType.type())); ImmutableList<PropertyDescriptor> descriptors = (ourFeatureType == null ? theirFeatureType : ourFeatureType).sortedDescriptors(); for (Entry<String, JsonElement> entry : merges.entrySet()) { int descriptorIndex = getDescriptorIndex(entry.getKey(), descriptors); if (descriptorIndex != -1 && entry.getValue().isJsonObject()) { PropertyDescriptor descriptor = descriptors.get(descriptorIndex); JsonObject attributeObject = entry.getValue().getAsJsonObject(); if (attributeObject.has("ours") && attributeObject.get("ours").isJsonPrimitive() && attributeObject.get("ours").getAsBoolean()) { featureBuilder.set(descriptor.getName(), ourFeature == null ? null : ourFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("theirs") && attributeObject.get("theirs").isJsonPrimitive() && attributeObject.get("theirs").getAsBoolean()) { featureBuilder.set(descriptor.getName(), theirFeature == null ? null : theirFeature.getValues().get(descriptorIndex).orNull()); } else if (attributeObject.has("value") && attributeObject.get("value").isJsonPrimitive()) { JsonPrimitive primitive = attributeObject.get("value").getAsJsonPrimitive(); if (primitive.isString()) { try { Object object = valueFromString( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsString()); featureBuilder.set(descriptor.getName(), object); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isNumber()) { try { Object value = valueFromNumber( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsNumber()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isBoolean()) { try { Object value = valueFromBoolean( FieldType.forBinding(descriptor.getType().getBinding()), primitive.getAsBoolean()); featureBuilder.set(descriptor.getName(), value); } catch (Exception e) { throw new Exception("Unable to convert attribute (" + entry.getKey() + ") to required type: " + descriptor.getType().getBinding().toString()); } } else if (primitive.isJsonNull()) { featureBuilder.set(descriptor.getName(), null); } else { throw new Exception( "Unsupported JSON type for attribute value (" + entry.getKey() + ")"); } } } } SimpleFeature feature = featureBuilder.buildFeature(NodeRef.nodeFromPath(featureId)); RevFeature revFeature = RevFeatureBuilder.build(feature); ggit.getRepository().getIndex().getDatabase().put(revFeature); return new StringRepresentation(revFeature.getId().toString(), MediaType.TEXT_PLAIN); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.gogoup.dddutils.misc.CodingHelper.java
License:Apache License
public static Object getObjectFromJson(JsonPrimitive value) { if (value.isString()) { return value.getAsString(); } else if (value.isBoolean()) { return value.getAsBoolean(); } else if (value.isNumber()) { return value.getAsNumber(); } else if (value.isJsonNull()) { return null; } else if (value.isJsonArray()) { JsonArray objArray = value.getAsJsonArray(); Object[] values = new Object[objArray.size()]; for (int i = 0; i < values.length; i++) { values[i] = getObjectFromJson(objArray.get(i).getAsJsonPrimitive()); }//from w ww . java 2s. c om return values; } else { throw new IllegalArgumentException("value"); } }
From source file:org.helios.dashkuj.core.apiimpl.AbstractDashku.java
License:Open Source License
/** * Builds a post body in post body format to send the dirty fields for the passed domain object. * The field values are URL encoded. //from w w w . j ava 2 s . c o m * @param domainObject the domain object to generate the diff post for * @return the diff post body */ protected Buffer buildDirtyUpdatePost(AbstractDashkuDomainObject domainObject) { StringBuilder b = new StringBuilder(); JsonObject jsonDomainObject = GsonFactory.getInstance().newNoSerGson().toJsonTree(domainObject) .getAsJsonObject(); Set<String> fieldnames = domainObject.getDirtyFieldNames(); if (fieldnames.isEmpty()) return null; for (String dirtyFieldName : domainObject.getDirtyFieldNames()) { try { JsonPrimitive jp = jsonDomainObject.getAsJsonPrimitive(dirtyFieldName); String value = null; if (jp.isString()) { value = URLEncoder.encode(jp.getAsString(), "UTF-8"); } else if (jp.isNumber()) { value = "" + jp.getAsNumber(); } else if (jp.isBoolean()) { value = "" + jp.getAsBoolean(); } else { value = jp.toString(); } b.append(dirtyFieldName).append("=").append(value).append("&"); } catch (Exception ex) { throw new RuntimeException("Failed to encode dirty field [" + dirtyFieldName + "]", ex); } } b.deleteCharAt(b.length() - 1); try { String encoded = b.toString(); //URLEncoder.encode(b.toString(), "UTF-8"); log.info("Update Post:[\n\t{}\n]", encoded); return new Buffer(encoded); } catch (Exception e) { throw new RuntimeException(e); // ain't happening } }