Java Code Examples for com.google.gson.JsonPrimitive#getAsDouble()

The following examples show how to use com.google.gson.JsonPrimitive#getAsDouble() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Utilities.java    From synthea with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a JsonPrimitive into a primitive Boolean, Double, or String.
 *
 * @param p
 *          : JsonPrimitive
 * @return Boolean, Double, or String
 */
public static Object primitive(JsonPrimitive p) {
  Object retVal = null;
  if (p.isBoolean()) {
    retVal = p.getAsBoolean();
  } else if (p.isNumber()) {
    double doubleVal = p.getAsDouble();

    if (doubleVal == Math.rint(doubleVal)) {
      retVal = (int) doubleVal;
    } else {
      retVal = doubleVal;
    }
  } else if (p.isString()) {
    retVal = p.getAsString();
  }
  return retVal;
}
 
Example 2
Source File: JSONRequestParser.java    From carbon-identity-framework with Apache License 2.0 6 votes vote down vote up
/**
 * Converts a given <code>{@link JsonElement}</code> to a <code>String</code> DataType
 * Predicted based on XACML 3.0 JSON profile
 *
 * @param element
 * @return
 */
private static String jsonElementToDataType(JsonPrimitive element) {
    if (element.isString()) {
        return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_STRING;
    } else if (element.isBoolean()) {
        return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_BOOLEAN;
    } else if (element.isNumber()) {
        double n1 = element.getAsDouble();
        int n2 = element.getAsInt();
        if (Math.ceil(n1) == n2) {
            return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_INTEGER;
        } else {
            return EntitlementEndpointConstants.ATTRIBUTE_DATA_TYPE_DOUBLE;
        }
    }

    return null;
}
 
Example 3
Source File: LwM2mNodeDeserializer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Object deserializeValue(JsonPrimitive val, org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
    switch (expectedType) {
    case BOOLEAN:
        return val.getAsBoolean();
    case STRING:
        return val.getAsString();
    case INTEGER:
        return val.getAsLong();
    case FLOAT:
        return val.getAsDouble();
    case TIME:
    case OPAQUE:
    default:
        // TODO we need to better handle this.
        return val.getAsString();
    }
}
 
Example 4
Source File: GsonJsonRpcUnmarshaller.java    From che with Eclipse Public License 2.0 6 votes vote down vote up
private Object getInnerItem(JsonElement jsonElement) {
  if (jsonElement.isJsonNull()) {
    return null;
  }

  if (jsonElement.isJsonObject()) {
    return jsonElement.getAsJsonObject();
  }

  if (jsonElement.isJsonPrimitive()) {
    JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();
    if (jsonPrimitive.isNumber()) {
      return jsonPrimitive.getAsDouble();
    } else if (jsonPrimitive.isString()) {
      return jsonPrimitive.getAsString();
    } else {
      return jsonPrimitive.getAsBoolean();
    }
  }

  throw new IllegalStateException("Unexpected json element type");
}
 
Example 5
Source File: LwM2mNodeDeserializer.java    From SI with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private Object deserializeValue(JsonPrimitive val, org.eclipse.leshan.core.model.ResourceModel.Type expectedType) {
    switch (expectedType) {
    case BOOLEAN:
        return val.getAsBoolean();
    case STRING:
        return val.getAsString();
    case INTEGER:
        return val.getAsLong();
    case FLOAT:
        return val.getAsDouble();
    case TIME:
    case OPAQUE:
    default:
        // TODO we need to better handle this.
        return val.getAsString();
    }
}
 
Example 6
Source File: JsonAttributeValueSerialization.java    From XACML with MIT License 6 votes vote down vote up
private static StdAttributeValue<?> parsePrimitiveAttribute(JsonPrimitive jsonPrimitive) {
	try {
		if (jsonPrimitive.isString()) {
			return new StdAttributeValue<>(XACML3.ID_DATATYPE_STRING, jsonPrimitive.getAsString());
		} else if (jsonPrimitive.isBoolean()) {
			return new StdAttributeValue<>(XACML3.ID_DATATYPE_BOOLEAN, jsonPrimitive.getAsBoolean());
		} else if (jsonPrimitive.isNumber()) {
			Number number = jsonPrimitive.getAsNumber();
			logger.debug("Number is {} {} ceil {}", number.doubleValue(), number.longValue(), Math.ceil(number.doubleValue()));
			if (Math.ceil(number.doubleValue()) == number.longValue()) {
				return new StdAttributeValue<>(XACML3.ID_DATATYPE_INTEGER, DataTypeInteger.newInstance().convert(jsonPrimitive.getAsInt()));
			} else {
				return new StdAttributeValue<>(XACML3.ID_DATATYPE_DOUBLE, jsonPrimitive.getAsDouble());
			}
		}
	} catch (DataTypeException e) {
		logger.error("Parse primitive failed", e);
	}
	return null;
}
 
Example 7
Source File: BetterJsonObject.java    From Hyperium with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 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
 *
 * @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;
}
 
Example 8
Source File: JsonUtil.java    From java-trader with Apache License 2.0 5 votes vote down vote up
public static Object json2value(JsonElement json) {
    Object result = null;
    if ( json.isJsonNull() ) {
        result = null;
    }else if ( json.isJsonObject() ) {
        JsonObject json0 = (JsonObject)json;
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        for(String key:json0.keySet()) {
            map.put(key, json2value(json0.get(key)));
        }
        result = map;
    }else if ( json.isJsonArray() ) {
        JsonArray arr = (JsonArray)json;
        ArrayList<Object> list = new ArrayList<>(arr.size());
        for(int i=0;i<arr.size();i++) {
            list.add(json2value(arr.get(i)));
        }
        result = list;
    } else if ( json.isJsonPrimitive() ) {
        JsonPrimitive p = (JsonPrimitive)json;
        if ( p.isBoolean() ) {
            result = p.getAsBoolean();
        }else if ( p.isNumber() ) {
            result = p.getAsDouble();
        }else if ( p.isString()) {
            result = p.getAsString();
        }else {
            result = p.getAsString();
        }
    }
    return result;
}
 
Example 9
Source File: GsonObjectDeserializer.java    From qaf with MIT License 5 votes vote down vote up
public static Object read(JsonElement in) {

		if (in.isJsonArray()) {
			List<Object> list = new ArrayList<Object>();
			JsonArray arr = in.getAsJsonArray();
			for (JsonElement anArr : arr) {
				list.add(read(anArr));
			}
			return list;
		} else if (in.isJsonObject()) {
			Map<String, Object> map = new LinkedTreeMap<String, Object>();
			JsonObject obj = in.getAsJsonObject();
			Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
			for (Map.Entry<String, JsonElement> entry : entitySet) {
				map.put(entry.getKey(), read(entry.getValue()));
			}
			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()) {
				if (prim.getAsString().contains("."))
					return prim.getAsDouble();
				else {
					return prim.getAsLong();
				}
			}
		}
		return null;
	}
 
Example 10
Source File: LwM2mNodeDeserializer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
    if (val.isBoolean())
        return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
    if (val.isString())
        return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
    if (val.isNumber()) {
        if (val.getAsDouble() == (double) val.getAsLong()) {
            return org.eclipse.leshan.core.model.ResourceModel.Type.INTEGER;
        } else {
            return org.eclipse.leshan.core.model.ResourceModel.Type.FLOAT;
        }
    }
    // use string as default value
    return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
}
 
Example 11
Source File: LwM2mNodeDeserializer.java    From SI with BSD 2-Clause "Simplified" License 5 votes vote down vote up
private org.eclipse.leshan.core.model.ResourceModel.Type getTypeFor(JsonPrimitive val) {
    if (val.isBoolean())
        return org.eclipse.leshan.core.model.ResourceModel.Type.BOOLEAN;
    if (val.isString())
        return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
    if (val.isNumber()) {
        if (val.getAsDouble() == (double) val.getAsLong()) {
            return org.eclipse.leshan.core.model.ResourceModel.Type.INTEGER;
        } else {
            return org.eclipse.leshan.core.model.ResourceModel.Type.FLOAT;
        }
    }
    // use string as default value
    return org.eclipse.leshan.core.model.ResourceModel.Type.STRING;
}
 
Example 12
Source File: QueryOptions.java    From yawp with MIT License 5 votes vote down vote up
private Object getJsonObjectValue(JsonElement jsonElement) {
    if (jsonElement.isJsonArray()) {
        return getJsonObjectValueForArrays(jsonElement);
    }
    if (jsonElement.isJsonNull()) {
        return null;
    }

    JsonPrimitive jsonPrimitive = jsonElement.getAsJsonPrimitive();

    if (jsonPrimitive.isNumber()) {
        if (jsonPrimitive.getAsString().indexOf(".") != -1) {
            return jsonPrimitive.getAsDouble();
        }
        return jsonPrimitive.getAsLong();
    }

    if (jsonPrimitive.isString()) {
        return jsonPrimitive.getAsString();
    }

    if (jsonPrimitive.isBoolean()) {
        return jsonPrimitive.getAsBoolean();
    }

    // TODO timestamp
    throw new RuntimeException("Invalid json value: " + jsonPrimitive.getAsString());
}
 
Example 13
Source File: JsonUtil.java    From olca-app with Mozilla Public License 2.0 5 votes vote down vote up
public static Double getDouble(JsonElement element, String property, Double defaultValue) {
	JsonElement value = getValue(element, property);
	if (!value.isJsonPrimitive())
		return defaultValue;
	JsonPrimitive primitive = value.getAsJsonPrimitive();
	if (primitive.isNumber())
		return primitive.getAsDouble();
	if (!primitive.isString())
		return defaultValue;
	try {
		return Double.parseDouble(primitive.getAsString());
	} catch (NumberFormatException e) {
		return defaultValue;
	}
}
 
Example 14
Source File: GsonDeserializerObjectWrapper.java    From qaf with MIT License 4 votes vote down vote up
private Object read(JsonElement in, Type typeOfT) {
	
	if (in.isJsonArray()) {
		JsonArray arr = in.getAsJsonArray();

		boolean isArray = isArray(typeOfT);
		Collection<Object> list = isArray ? new ArrayList<Object>()
				: context.deserialize(new JsonArray(0), typeOfT);
		for (JsonElement anArr : arr) {
			((Collection<Object>) list).add(read(anArr, getTypeArguments(typeOfT, 0)));
		}
		if (isArray) {
			return toArray((List<Object>) list);
		}
		try {
			return ClassUtil.getClass(typeOfT).cast(list);
		} catch (Exception e) {
			return context.deserialize(in, typeOfT);
		}
	} else if (in.isJsonObject()
			&& (isAssignableFrom(typeOfT, Map.class) || ClassUtil.getClass(typeOfT).equals(Object.class))) {
		Map<Object, Object> map = context.deserialize(new JsonObject(), typeOfT);//new LinkedTreeMap<Object, Object>();
		JsonObject obj = in.getAsJsonObject();
		Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet();
		for (Map.Entry<String, JsonElement> entry : entitySet) {
			map.put(entry.getKey(), read(entry.getValue(), getTypeArguments(typeOfT, 1)));
		}
		return map;
	} else if (in.isJsonPrimitive() && ClassUtil.getClass(typeOfT).equals(Object.class)) {
		JsonPrimitive prim = in.getAsJsonPrimitive();
		if (prim.isBoolean()) {
			return prim.getAsBoolean();
		} else if (prim.isString()) {
			return prim.getAsString();
		} else if (prim.isNumber()) {
			if (prim.getAsString().contains("."))
				return prim.getAsDouble();
			else {
				return prim.getAsLong();
			}
		}
	}
	return context.deserialize(in, typeOfT);
}
 
Example 15
Source File: JavaModelFactory.java    From swellrt with Apache License 2.0 4 votes vote down vote up
@Override
public Object traverseJsonObject(Object o, String path) {

  if (o == null)
    return null;

  JsonElement e = (JsonElement) o;

  if (path == null || path.isEmpty()) {

    if (e.isJsonPrimitive()) {
      JsonPrimitive p = (JsonPrimitive) e;

      if (p.isBoolean())
        return new Boolean(p.getAsBoolean());
      else if (p.isNumber())
        return new Double(p.getAsDouble());
      else if (p.isString())
        return new String(p.getAsString());
      else
        return null;

    } else
      return e;
  }

  String propName = path.indexOf(".") != -1 ? path.substring(0, path.indexOf(".")) : path;
  String restPath = path.indexOf(".") != -1 ? path.substring(path.indexOf(".") + 1) : null;

  JsonElement propValue = null;
  if (e.isJsonObject()) {

    JsonObject object = (JsonObject) e;
    propValue = object.get(propName);
    return traverseJsonObject(propValue, restPath);

  } else if (e.isJsonArray()) {
    try {
      int index = Integer.parseInt(propName);
      JsonArray array = (JsonArray) e;
      return traverseJsonObject(array.get(index), restPath);
    } catch (NumberFormatException ex) {
      return null;
    }

  } else if (e.isJsonPrimitive()) {
    return null;
  }


  return null;
}
 
Example 16
Source File: SNodeGson.java    From swellrt with Apache License 2.0 3 votes vote down vote up
public static SNode castToSNode(JsonElement object) {

    Preconditions.checkArgument(object != null, "Null argument");

    if (object.isJsonPrimitive()) {

      JsonPrimitive primitiveObject = object.getAsJsonPrimitive();

      if (primitiveObject.isBoolean()) {

        return new SPrimitive(primitiveObject.getAsBoolean(), new SNodeAccessControl());

      } else if (primitiveObject.isNumber()) {

        return new SPrimitive(primitiveObject.getAsDouble(), new SNodeAccessControl());

      } else if (primitiveObject.isString()) {

        return new SPrimitive(primitiveObject.isString(), new SNodeAccessControl());

      }

    } else if (object.isJsonObject()) {

      return SMapGson.create(object.getAsJsonObject());

    } else if (object.isJsonArray()) {

      return SListGson.create(object.getAsJsonArray());

    }

    throw new IllegalStateException("Unable to cast object to JS native SNode");
  }