List of usage examples for com.google.gson JsonPrimitive getAsDouble
@Override public double getAsDouble()
From source file:com.softwarementors.extjs.djn.router.processor.standard.json.JsonRequestProcessor.java
License:Open Source License
private @CheckForNull Object toSimpleJavaType(JsonElement jsonValue) { if (jsonValue == null) return null; //VR Object value = null;//w ww.ja v a2 s. c o m if (!jsonValue.isJsonNull()) { if (jsonValue.isJsonPrimitive()) { JsonPrimitive primitive = jsonValue.getAsJsonPrimitive(); if (primitive.isBoolean()) { value = Boolean.valueOf(primitive.getAsBoolean()); } else if (primitive.isNumber()) { value = Double.valueOf(primitive.getAsDouble()); } else if (primitive.isString()) { value = primitive.getAsString(); } else { throw UnexpectedException.forUnexpectedCodeBranchExecuted(); } } else if (jsonValue.isJsonArray()) { //This simply does not work (?) JsonArray array = jsonValue.getAsJsonArray(); Object[] result = new Object[array.size()]; for (int i = 0; i < array.size(); i++) { result[i] = toSimpleJavaType(array.get(i)); } value = result; } else if (jsonValue.isJsonObject()) { //This simply does not work (?) //value = getGson().fromJson(jsonValue, Map.class ); JsonObject obj = jsonValue.getAsJsonObject(); Iterator<Entry<String, JsonElement>> properties = obj.entrySet().iterator(); Map<String, Object> result = new HashMap<String, Object>(); while (properties.hasNext()) { Entry<String, JsonElement> property = properties.next(); JsonElement propertyValue = property.getValue(); result.put(property.getKey(), toSimpleJavaType(propertyValue)); } value = result; } else { throw UnexpectedException.forUnexpectedCodeBranchExecuted(); } } return value; }
From source file:cosmos.records.JsonRecords.java
License:Apache License
/** * Parses a {@link JsonObject{ into a MapRecord. A duplicate key in the JsonObject will * overwrite the previous key./* ww w. java2 s.com*/ * @param map The JsonObject being parsed * @param generator Construct to generate a docId for this {@link MapRecord} * @return A MapRecord built from the {@link JsonObject} */ protected static MapRecord asMapRecord(JsonObject map, DocIdGenerator generator) { Map<Column, RecordValue<?>> data = Maps.newHashMap(); for (Entry<String, JsonElement> entry : map.entrySet()) { final Column key = Column.create(entry.getKey()); final JsonElement value = entry.getValue(); if (value.isJsonNull()) { data.put(key, null); } else if (value.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) value; // Numbers if (primitive.isNumber()) { NumberRecordValue<?> v; double d = primitive.getAsDouble(); if ((int) d == d) { v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS); } else if ((long) d == d) { v = new LongRecordValue((long) d, Defaults.EMPTY_VIS); } else { v = new DoubleRecordValue(d, Defaults.EMPTY_VIS); } data.put(key, v); } else if (primitive.isString()) { // String data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS)); } else if (primitive.isBoolean()) { // Boolean data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS)); } else if (primitive.isJsonNull()) { // Is this redundant? data.put(key, null); } else { throw new RuntimeException("Unhandled primitive: " + primitive); } } else { throw new RuntimeException("Expected a String, Number or Boolean"); } } return new MapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS); }
From source file:cosmos.records.JsonRecords.java
License:Apache License
/** * Builds a {@link MultimapRecord} from the provided {@link JsonObject} using a docid * from the {@link DocIdGenerator}. This method will support lists of values for a key * in the {@link JsonObject} but will fail on values which are {@link JsonObject}s and * values which have nested {@link JsonArray}s. * @param map The {@link JsonObject} to build this {@link MultimapRecord} from * @param generator {@link DocIdGenerator} to construct a docid for this {@link MultimapRecord} * @return A {@link MultimapRecord} built from the provided arguments. *///w w w. ja v a2 s .c o m protected static MultimapRecord asMultimapRecord(JsonObject map, DocIdGenerator generator) { Multimap<Column, RecordValue<?>> data = HashMultimap.create(); for (Entry<String, JsonElement> entry : map.entrySet()) { final Column key = Column.create(entry.getKey()); final JsonElement value = entry.getValue(); if (value.isJsonNull()) { data.put(key, null); } else if (value.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) value; // Numbers if (primitive.isNumber()) { NumberRecordValue<?> v; double d = primitive.getAsDouble(); if ((int) d == d) { v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS); } else if ((long) d == d) { v = new LongRecordValue((long) d, Defaults.EMPTY_VIS); } else { v = new DoubleRecordValue(d, Defaults.EMPTY_VIS); } data.put(key, v); } else if (primitive.isString()) { // String data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS)); } else if (primitive.isBoolean()) { // Boolean data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS)); } else if (primitive.isJsonNull()) { // Is this redundant? data.put(key, null); } else { throw new RuntimeException("Unhandled primitive: " + primitive); } } else if (value.isJsonArray()) { // Multimaps should handle the multiple values, not fail JsonArray values = value.getAsJsonArray(); for (JsonElement element : values) { if (element.isJsonNull()) { data.put(key, null); } else if (element.isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) element; // Numbers if (primitive.isNumber()) { NumberRecordValue<?> v; double d = primitive.getAsDouble(); if ((int) d == d) { v = new IntegerRecordValue((int) d, Defaults.EMPTY_VIS); } else if ((long) d == d) { v = new LongRecordValue((long) d, Defaults.EMPTY_VIS); } else { v = new DoubleRecordValue(d, Defaults.EMPTY_VIS); } data.put(key, v); } else if (primitive.isString()) { // String data.put(key, new StringRecordValue(primitive.getAsString(), Defaults.EMPTY_VIS)); } else if (primitive.isBoolean()) { // Boolean data.put(key, new BooleanRecordValue(primitive.getAsBoolean(), Defaults.EMPTY_VIS)); } else if (primitive.isJsonNull()) { // Is this redundant? data.put(key, null); } else { throw new RuntimeException("Unhandled Json primitive: " + primitive); } } else { throw new RuntimeException("Expected a Json primitive"); } } } else { throw new RuntimeException("Expected a String, Number or Boolean"); } } return new MultimapRecord(data, generator.getDocId(data), Defaults.EMPTY_VIS); }
From source file:de.innovationgate.wgpublisher.webtml.utils.JsonUtils.java
License:Open Source License
public Object jsonToJava(JsonElement jsonValue) { Object value = null;//w w w . j a v a 2 s .c o m if (jsonValue.isJsonNull()) { value = null; } else if (jsonValue.isJsonPrimitive()) { JsonPrimitive prim = (JsonPrimitive) jsonValue; if (prim.isNumber()) { value = prim.getAsDouble(); } else if (prim.isBoolean()) { value = prim.getAsBoolean(); } else { value = prim.getAsString(); } value = jsonToJavaConversions(value); } else if (jsonValue.isJsonArray()) { JsonArray array = jsonValue.getAsJsonArray(); List<Object> list = new ArrayList<Object>(); for (JsonElement element : array) { list.add(jsonToJava(element)); } } else if (jsonValue.isJsonObject()) { JsonObject obj = jsonValue.getAsJsonObject(); Map<String, Object> map = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : obj.entrySet()) { map.put(String.valueOf(entry.getKey()), jsonToJava(entry.getValue())); } } return value; }
From source file:leola.web.WebLeolaLibrary.java
License:Open Source License
/** * Converts the {@link JsonElement} into the equivalent {@link LeoObject} * //from w w w . j a va2 s . c om * @param element * @return the {@link LeoObject} */ private static LeoObject toLeoObject(JsonElement element) { if (element == null || element.isJsonNull()) { return LeoObject.NULL; } if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); LeoArray leoArray = new LeoArray(array.size()); array.forEach(e -> leoArray.add(toLeoObject(e))); return leoArray; } if (element.isJsonObject()) { JsonObject object = element.getAsJsonObject(); LeoMap leoMap = new LeoMap(); object.entrySet().forEach(entry -> { leoMap.putByString(entry.getKey(), toLeoObject(entry.getValue())); }); return leoMap; } if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return LeoObject.valueOf(primitive.getAsBoolean()); } if (primitive.isNumber()) { return LeoObject.valueOf(primitive.getAsDouble()); } if (primitive.isString()) { return LeoString.valueOf(primitive.getAsString()); } } return LeoObject.NULL; }
From source file:me.boomboompower.togglechat.utils.BetterJsonObject.java
License:Open Source License
/** * The optional double method, returns the default value if * the key is null, empty or the data does not contain * the key. This will also return the default value if * the data value is not a number//from www. ja v a 2s . c o m * * @param key the key the value will be loaded from * @return the value in the json data set or the default if the key cannot be found */ public double optDouble(String key, double value) { if (key == null || key.isEmpty() || !has(key)) { return value; } JsonPrimitive primitive = asPrimitive(get(key)); try { if (primitive != null && primitive.isNumber()) { return primitive.getAsDouble(); } } catch (NumberFormatException ignored) { } return value; }
From source file:net.nexustools.njs.JSON.java
License:Open Source License
public JSON(final Global global) { super(global); setHidden("stringify", new AbstractFunction(global) { public java.lang.String stringify(BaseObject object) { StringBuilder builder = new StringBuilder(); stringify(object, builder);//from www .ja v a2 s . com return builder.toString(); } public void stringify(BaseObject object, StringBuilder builder) { if (Utilities.isUndefined(object)) { builder.append("null"); return; } BaseObject toJSON = object.get("toJSON", OR_NULL); if (toJSON != null) stringify0(((BaseFunction) toJSON).call(object), builder); else stringify0(object, builder); } public void stringify0(BaseObject object, StringBuilder builder) { if (object instanceof GenericArray) { builder.append('['); if (((GenericArray) object).length() > 0) { stringify(object.get(0), builder); for (int i = 1; i < ((GenericArray) object).length(); i++) { builder.append(','); stringify(object.get(i), builder); } } builder.append(']'); } else if (object instanceof String.Instance) { builder.append('"'); builder.append(object.toString()); builder.append('"'); } else if (object instanceof Number.Instance) { double number = ((Number.Instance) object).value; if (Double.isNaN(number) || Double.isInfinite(number)) builder.append("null"); builder.append(object.toString()); } else if (object instanceof Boolean.Instance) builder.append(object.toString()); else { builder.append('{'); Iterator<java.lang.String> it = object.keys().iterator(); if (it.hasNext()) { java.lang.String key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); if (it.hasNext()) { do { builder.append(','); key = it.next(); builder.append('"'); builder.append(key); builder.append("\":"); stringify(object.get(key), builder); } while (it.hasNext()); } } builder.append('}'); } } @Override public BaseObject call(BaseObject _this, BaseObject... params) { switch (params.length) { case 0: return Undefined.INSTANCE; case 1: if (params[0] == Undefined.INSTANCE) return Undefined.INSTANCE; return global.wrap(stringify(params[0])); default: return global.wrap("undefined"); } } @Override public java.lang.String name() { return "JSON_stringify"; } }); setHidden("parse", new AbstractFunction(global) { final Gson GSON; { GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(BaseObject.class, new JsonDeserializer<BaseObject>() { @Override public BaseObject deserialize(JsonElement je, Type type, JsonDeserializationContext jdc) throws JsonParseException { if (je.isJsonNull()) return Null.INSTANCE; if (je.isJsonPrimitive()) { JsonPrimitive primitive = je.getAsJsonPrimitive(); if (primitive.isBoolean()) return primitive.getAsBoolean() ? global.Boolean.TRUE : global.Boolean.FALSE; if (primitive.isNumber()) return global.wrap(primitive.getAsDouble()); if (primitive.isString()) return global.wrap(primitive.getAsString()); throw new UnsupportedOperationException(primitive.toString()); } if (je.isJsonObject()) { GenericObject go = new GenericObject(global); JsonObject jo = je.getAsJsonObject(); for (Map.Entry<java.lang.String, JsonElement> entry : jo.entrySet()) { go.set(entry.getKey(), deserialize(entry.getValue(), type, jdc)); } return go; } if (je.isJsonArray()) { JsonArray ja = je.getAsJsonArray(); BaseObject[] array = new BaseObject[ja.size()]; for (int i = 0; i < array.length; i++) { array[i] = deserialize(ja.get(i), type, jdc); } return new GenericArray(global, array); } throw new UnsupportedOperationException(je.toString()); } }); GSON = gsonBuilder.create(); } @Override public BaseObject call(BaseObject _this, BaseObject... params) { try { return GSON.fromJson(params[0].toString(), BaseObject.class); } catch (com.google.gson.JsonSyntaxException ex) { throw new Error.JavaException("SyntaxError", "Unexpected token", ex); } } @Override public java.lang.String name() { return "JSON_parse"; } }); }
From source file:org.apache.airavata.common.utils.JSONUtil.java
License:Apache License
private static boolean isEqual(JsonPrimitive primitiveOrig, JsonPrimitive primitiveNew) { if (primitiveOrig == null && primitiveNew == null) { return true; } else if (primitiveOrig == null || primitiveNew == null) { return false; } else {/* w w w .ja va 2 s. c o m*/ if (primitiveOrig.isString() && primitiveNew.isString()) { if (!primitiveOrig.getAsString().equals(primitiveNew.getAsString())) { return false; } } else if (primitiveOrig.isBoolean() && primitiveNew.isBoolean()) { if ((Boolean.valueOf(primitiveOrig.getAsBoolean()).compareTo(primitiveNew.getAsBoolean()) != 0)) { return false; } } else if (primitiveOrig.isNumber() && primitiveNew.isNumber()) { if (new Double(primitiveOrig.getAsDouble()).compareTo(primitiveNew.getAsDouble()) != 0) { return false; } } else { return primitiveOrig.isJsonNull() && primitiveNew.isJsonNull(); } } return true; }
From source file:org.apache.orc.tools.json.JsonSchemaFinder.java
License:Apache License
static HiveType pickType(JsonElement json) { if (json.isJsonPrimitive()) { JsonPrimitive prim = (JsonPrimitive) json; if (prim.isBoolean()) { return new BooleanType(); } else if (prim.isNumber()) { Matcher matcher = DECIMAL_PATTERN.matcher(prim.getAsString()); if (matcher.matches()) { int intDigits = matcher.group("int").length(); String fraction = matcher.group("fraction"); int scale = fraction == null ? 0 : fraction.length(); if (scale == 0) { if (intDigits < 19) { long value = prim.getAsLong(); if (value >= -128 && value < 128) { return new NumericType(HiveType.Kind.BYTE, intDigits, scale); } else if (value >= -32768 && value < 32768) { return new NumericType(HiveType.Kind.SHORT, intDigits, scale); } else if (value >= -2147483648 && value < 2147483648L) { return new NumericType(HiveType.Kind.INT, intDigits, scale); } else { return new NumericType(HiveType.Kind.LONG, intDigits, scale); }/*w w w . j a v a 2 s . co m*/ } else if (intDigits == 19) { // at 19 digits, it may fit inside a long, but we need to check BigInteger val = prim.getAsBigInteger(); if (val.compareTo(MIN_LONG) >= 0 && val.compareTo(MAX_LONG) <= 0) { return new NumericType(HiveType.Kind.LONG, intDigits, scale); } } } if (intDigits + scale <= MAX_DECIMAL_DIGITS) { return new NumericType(HiveType.Kind.DECIMAL, intDigits, scale); } } double value = prim.getAsDouble(); if (value >= Float.MIN_VALUE && value <= Float.MAX_VALUE) { return new NumericType(HiveType.Kind.FLOAT, 0, 0); } else { return new NumericType(HiveType.Kind.DOUBLE, 0, 0); } } else { String str = prim.getAsString(); if (TIMESTAMP_PATTERN.matcher(str).matches()) { return new StringType(HiveType.Kind.TIMESTAMP); } else if (HEX_PATTERN.matcher(str).matches()) { return new StringType(HiveType.Kind.BINARY); } else { return new StringType(HiveType.Kind.STRING); } } } else if (json.isJsonNull()) { return new NullType(); } else if (json.isJsonArray()) { ListType result = new ListType(); result.elementType = new NullType(); for (JsonElement child : ((JsonArray) json)) { HiveType sub = pickType(child); if (result.elementType.subsumes(sub)) { result.elementType.merge(sub); } else if (sub.subsumes(result.elementType)) { sub.merge(result.elementType); result.elementType = sub; } else { result.elementType = new UnionType(result.elementType, sub); } } return result; } else { JsonObject obj = (JsonObject) json; StructType result = new StructType(); for (Map.Entry<String, JsonElement> field : obj.entrySet()) { String fieldName = field.getKey(); HiveType type = pickType(field.getValue()); result.fields.put(fieldName, type); } return result; } }
From source file:org.apache.qpid.disttest.json.PropertyValueAdapter.java
License:Apache License
@Override public PropertyValue deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; } else if (json.isJsonPrimitive()) { Object result = null;/* w w w . j ava2 s . c om*/ JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { result = primitive.getAsString(); } else if (primitive.isNumber()) { String asString = primitive.getAsString(); if (asString.indexOf('.') != -1 || asString.indexOf('e') != -1) { result = primitive.getAsDouble(); } else { result = primitive.getAsLong(); } } else if (primitive.isBoolean()) { result = primitive.getAsBoolean(); } else { throw new JsonParseException("Unsupported primitive value " + primitive); } return new SimplePropertyValue(result); } else if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); List<Object> result = new ArrayList<Object>(array.size()); for (JsonElement element : array) { result.add(context.deserialize(element, Object.class)); } return new SimplePropertyValue(result); } else if (json.isJsonObject()) { JsonObject object = json.getAsJsonObject(); JsonElement defElement = object.getAsJsonPrimitive(DEF_FIELD); Class<?> classInstance = null; if (defElement != null) { try { classInstance = _factory.getPropertyValueClass(defElement.getAsString()); } catch (ClassNotFoundException e) { // ignore } } if (classInstance == null) { Map<String, Object> result = new HashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : object.entrySet()) { Object value = context.deserialize(entry.getValue(), Object.class); result.put(entry.getKey(), value); } return new SimplePropertyValue(result); } else { return context.deserialize(json, classInstance); } } else { throw new JsonParseException("Unsupported JSON type " + json); } }