List of usage examples for com.google.gson JsonElement getAsDouble
public double getAsDouble()
From source file:net.doubledoordev.backend.util.TypeHellhole.java
License:Open Source License
public static void set(Field field, Object object, JsonElement value) throws Exception { if (field.getType() == byte.class) field.setByte(object, value.getAsByte()); else if (field.getType() == short.class) field.setShort(object, value.getAsShort()); else if (field.getType() == int.class) field.setInt(object, value.getAsInt()); else if (field.getType() == long.class) field.setLong(object, value.getAsLong()); else if (field.getType() == float.class) field.setFloat(object, value.getAsFloat()); else if (field.getType() == double.class) field.setDouble(object, value.getAsDouble()); else if (field.getType() == boolean.class) field.setBoolean(object, value.getAsBoolean()); else if (field.getType() == char.class) field.setChar(object, value.getAsCharacter()); ////from w w w.java 2 s. c o m else if (field.getType() == Byte.class) field.set(object, value.getAsByte()); else if (field.getType() == Short.class) field.set(object, value.getAsShort()); else if (field.getType() == Integer.class) field.set(object, value.getAsInt()); else if (field.getType() == Long.class) field.set(object, value.getAsLong()); else if (field.getType() == Float.class) field.set(object, value.getAsFloat()); else if (field.getType() == Double.class) field.set(object, value.getAsDouble()); else if (field.getType() == Boolean.class) field.set(object, value.getAsBoolean()); else if (field.getType() == Character.class) field.set(object, value.getAsCharacter()); // else if (field.getType() == String.class) field.set(object, value.getAsString()); else { String m = String.format("Unknown type! Field type: %s Json value: %s Data class: %s", field.getType(), value.toString(), object.getClass().getSimpleName()); Main.LOGGER.error(m); throw new Exception(m); } }
From source file:nl.pvanassen.highchart.api.serializer.NullableDoubleSerializer.java
License:Apache License
public NullableDouble deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { if (json.getAsString().equals("NullableDouble.NULL")) { return NullableDouble.NULL_INSTANCE; }//from ww w .j a va2 s . c o m return NullableDouble.of(json.getAsDouble()); }
From source file:org.apache.edgent.runtime.jsoncontrol.JsonControlService.java
License:Apache License
@SuppressWarnings({ "unchecked", "rawtypes" }) private Object[] getArguments(Method method, JsonArray args) { final Class<?>[] paramTypes = method.getParameterTypes(); if (paramTypes.length == 0 || args == null || args.size() == 0) return null; assert paramTypes.length == args.size(); Object[] oargs = new Object[paramTypes.length]; for (int i = 0; i < oargs.length; i++) { final Class<?> pt = paramTypes[i]; final JsonElement arg = args.get(i); Object jarg;//from w w w . ja va2s . c o m if (String.class == pt) { if (arg instanceof JsonObject) jarg = gson.toJson(arg); else jarg = arg.getAsString(); } else if (Integer.TYPE == pt) jarg = arg.getAsInt(); else if (Long.TYPE == pt) jarg = arg.getAsLong(); else if (Double.TYPE == pt) jarg = arg.getAsDouble(); else if (Boolean.TYPE == pt) jarg = arg.getAsBoolean(); else if (pt.isEnum()) jarg = Enum.valueOf((Class<Enum>) pt, arg.getAsString()); else throw new UnsupportedOperationException(pt.getName()); oargs[i] = jarg; } return oargs; }
From source file:org.apache.gobblin.converter.grok.GrokToJsonConverter.java
License:Apache License
@VisibleForTesting JsonObject createOutput(JsonArray outputSchema, String inputRecord) throws DataConversionException { JsonObject outputRecord = new JsonObject(); Match gm = grok.match(inputRecord);//www . j a va 2 s . c o m gm.captures(); JsonElement capturesJson = JSON_PARSER.parse(gm.toJson()); for (JsonElement anOutputSchema : outputSchema) { JsonObject outputSchemaJsonObject = anOutputSchema.getAsJsonObject(); String key = outputSchemaJsonObject.get(COLUMN_NAME_KEY).getAsString(); String type = outputSchemaJsonObject.getAsJsonObject(DATA_TYPE).get(TYPE_KEY).getAsString(); if (isFieldNull(capturesJson, key)) { if (!outputSchemaJsonObject.get(NULLABLE).getAsBoolean()) { throw new DataConversionException( "Field " + key + " is null or not exists but it is non-nullable by the schema."); } outputRecord.add(key, JsonNull.INSTANCE); } else { JsonElement jsonElement = capturesJson.getAsJsonObject().get(key); switch (type) { case "int": outputRecord.addProperty(key, jsonElement.getAsInt()); break; case "long": outputRecord.addProperty(key, jsonElement.getAsLong()); break; case "double": outputRecord.addProperty(key, jsonElement.getAsDouble()); break; case "float": outputRecord.addProperty(key, jsonElement.getAsFloat()); break; case "boolean": outputRecord.addProperty(key, jsonElement.getAsBoolean()); break; case "string": default: outputRecord.addProperty(key, jsonElement.getAsString()); } } } return outputRecord; }
From source file:org.apache.lens.driver.es.client.jest.JestResultSetTransformer.java
License:Apache License
protected Object getTypedValue(int colPosition, JsonElement jsonObjectValue) { final Type type = getDataType(colPosition, jsonObjectValue); switch (type) { case NULL_TYPE: return null; case DOUBLE_TYPE: return jsonObjectValue.getAsDouble(); case BOOLEAN_TYPE: return jsonObjectValue.getAsBoolean(); default:/*w w w. java 2 s . c o m*/ return jsonObjectValue.getAsString(); } }
From source file:org.coinspark.wallet.CSAsset.java
License:Open Source License
private boolean parseJSONString(String JSONString) { if (JSONString == null) { return false; }/*w w w .j a v a 2s.c om*/ if (JSONString.length() > 0) { try { JsonElement jelement = new JsonParser().parse(JSONString); JsonObject jresult = jelement.getAsJsonObject(); JsonElement jvalue; // All JSON strings - from asset web page and from asset database jvalue = jresult.get("name"); if (jvalue != null) { name = jvalue.getAsString(); } jvalue = jresult.get("name_short"); if (jvalue != null) { nameShort = jvalue.getAsString(); } jvalue = jresult.get("issuer"); if (jvalue != null) { issuer = jvalue.getAsString(); } jvalue = jresult.get("description"); if (jvalue != null) { description = jvalue.getAsString(); } jvalue = jresult.get("units"); if (jvalue != null) { units = jvalue.getAsString(); } jvalue = jresult.get("contract_url"); if (jvalue != null) { contractUrl = jvalue.getAsString(); } jvalue = jresult.get("coinspark_tracker_url"); if (jvalue != null) { if (jvalue.isJsonArray()) { JsonArray jarray = jvalue.getAsJsonArray(); if (jarray.size() > 0) { coinsparkTrackerUrls = new String[jarray.size()]; for (int i = 0; i < jarray.size(); i++) { JsonElement jvalueUrl = jarray.get(i); if (jvalueUrl != null) { coinsparkTrackerUrls[i] = CSUtils.addHttpIfMissing(jvalueUrl.getAsString()); } } } } else { coinsparkTrackerUrls = new String[] { CSUtils.addHttpIfMissing(jvalue.getAsString()) }; } } jvalue = jresult.get("issue_date"); if (jvalue != null) { issueDate = jvalue.getAsString(); } jvalue = jresult.get("expiry_date"); if (jvalue != null) { expiryDate = jvalue.getAsString(); } jvalue = jresult.get("interest_rate"); if (jvalue != null) { interestRate = jvalue.getAsDouble(); } jvalue = jresult.get("multiple"); if (jvalue != null) { multiple = jvalue.getAsDouble(); } jvalue = jresult.get("format"); if (jvalue != null) { format = jvalue.getAsString(); } jvalue = jresult.get("format_1"); if (jvalue != null) { format1 = jvalue.getAsString(); } jvalue = jresult.get("icon_url"); if (jvalue != null) { iconUrl = jvalue.getAsString(); } jvalue = jresult.get("image_url"); if (jvalue != null) { imageUrl = jvalue.getAsString(); } jvalue = jresult.get("feed_url"); if (jvalue != null) { feedUrl = jvalue.getAsString(); } jvalue = jresult.get("redemption_irl"); if (jvalue != null) { redemptionUrl = jvalue.getAsString(); } // From asset database only jvalue = jresult.get("asset_id"); if (jvalue != null) { assetID = jvalue.getAsInt(); } jvalue = jresult.get("date_created"); if (jvalue != null) { dateCreation = CSUtils.iso86012date(jvalue.getAsString()); } jvalue = jresult.get("asset_state"); if (jvalue != null) { assetState = CSAssetState.valueOf(jvalue.getAsString()); } jvalue = jresult.get("asset_source"); if (jvalue != null) { assetSource = CSAssetSource.valueOf(jvalue.getAsString()); } jvalue = jresult.get("asset_contract_state"); if (jvalue != null) { assetContractState = CSAssetContractState.valueOf(jvalue.getAsString()); } jvalue = jresult.get("gen_txid"); if (jvalue != null) { genTxID = jvalue.getAsString(); } jvalue = jresult.get("visible"); if (jvalue != null) { if (jvalue.getAsInt() == 0) { visible = false; } else { visible = true; } } jvalue = jresult.get("fsi_txid"); if (jvalue != null) { firstSpentTxID = jvalue.getAsString(); } jvalue = jresult.get("fsi_vout"); if (jvalue != null) { firstSpentVout = jvalue.getAsInt(); } jvalue = jresult.get("genesis"); if (jvalue != null) { genesis = new CoinSparkGenesis(); if (!genesis.decode(jvalue.getAsString())) { genesis = null; } } jvalue = jresult.get("asset_ref_block"); if (jvalue != null) { assetRef = new CoinSparkAssetRef(); assetRef.setBlockNum(jvalue.getAsInt()); jvalue = jresult.get("asset_ref_offset"); if (jvalue != null) { assetRef.setTxOffset(jvalue.getAsInt()); } jvalue = jresult.get("asset_ref_prefix"); if (jvalue != null) { assetRef.setTxIDPrefix(CSUtils.hex2Byte(jvalue.getAsString())); } } jvalue = jresult.get("valid_checked"); if (jvalue != null) { validChecked = CSUtils.iso86012date(jvalue.getAsString()); } jvalue = jresult.get("valid_failures"); if (jvalue != null) { validFailures = jvalue.getAsInt(); } jvalue = jresult.get("contract_path"); if (jvalue != null) { contractPath = jvalue.getAsString(); } jvalue = jresult.get("valid_contract_path"); if (jvalue != null) { validContractPath = jvalue.getAsString(); } jvalue = jresult.get("json_path"); if (jvalue != null) { jsonPath = jvalue.getAsString(); } jvalue = jresult.get("valid_json_path"); if (jvalue != null) { validJsonPathToSet = jvalue.getAsString(); } jvalue = jresult.get("contract_mime"); if (jvalue != null) { contractMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } jvalue = jresult.get("valid_contract_mime"); if (jvalue != null) { validContractMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } jvalue = jresult.get("image_path"); if (jvalue != null) { imagePath = jvalue.getAsString(); } jvalue = jresult.get("image_mime"); if (jvalue != null) { imageMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } jvalue = jresult.get("icon_path"); if (jvalue != null) { iconPath = jvalue.getAsString(); } jvalue = jresult.get("icon_mime"); if (jvalue != null) { iconMimeType = CSUtils.CSMimeType.fromExtension(jvalue.getAsString()); } } catch (JsonSyntaxException ex) { assetValidationState = CSAssetState.ASSET_SPECS_NOT_PARSED; log.info("Asset details: Error while parsing JSON String " + JSONString); return false; } } else { return false; } if (!checkRequiredFields()) { assetValidationState = CSAssetState.REQUIRED_FIELD_MISSING; return false; } return true; }
From source file:org.dashbuilder.dataprovider.backend.elasticsearch.rest.client.impl.jest.ElasticSearchJestClient.java
License:Apache License
/** * Parses a given value (for a given column type) returned by response JSON query body from EL server. * * @param column The data column definition. * @param valueElement The value element from JSON query response to format. * @return The formatted value for the given column type. *//* w ww .j ava 2 s. c om*/ public static Object parseValue(ElasticSearchDataSetDef definition, ElasticSearchDataSetMetadata metadata, DataColumn column, JsonElement valueElement) { if (column == null || valueElement == null || valueElement.isJsonNull()) return null; if (!valueElement.isJsonPrimitive()) throw new RuntimeException("Not expected JsonElement type to parse from query response."); JsonPrimitive valuePrimitive = valueElement.getAsJsonPrimitive(); ColumnType columnType = column.getColumnType(); if (ColumnType.NUMBER.equals(columnType)) { return valueElement.getAsDouble(); } else if (ColumnType.DATE.equals(columnType)) { // We can expect two return core types from EL server when handling dates: // 1.- String type, using the field pattern defined in the index' mappings, when it's result of a query without aggregations. // 2.- Numeric type, when it's result from a scalar function or a value pickup. if (valuePrimitive.isString()) { DateTimeFormatter formatter = null; String datePattern = metadata.getFieldPattern(column.getId()); if (datePattern == null || datePattern.trim().length() == 0) { // If no custom pattern for date field, use the default by EL -> org.joda.time.format.ISODateTimeFormat#dateOptionalTimeParser formatter = ElasticSearchDataSetProvider.EL_DEFAULT_DATETIME_FORMATTER; } else { // Obtain the date value by parsing using the EL pattern specified for this field. formatter = DateTimeFormat.forPattern(datePattern); } DateTime dateTime = formatter.parseDateTime(valuePrimitive.getAsString()); return dateTime.toDate(); } if (valuePrimitive.isNumber()) { return new Date(valuePrimitive.getAsLong()); } throw new UnsupportedOperationException( "Value core type not supported. Expecting string or number when using date core field types."); } // LABEL, TEXT or grouped DATE column types. String valueAsString = valueElement.getAsString(); ColumnGroup columnGroup = column.getColumnGroup(); // For FIXED date values, remove the unnecessary "0" at first character. (eg: replace month "01" to "1") if (columnGroup != null && GroupStrategy.FIXED.equals(columnGroup.getStrategy()) && valueAsString.startsWith("0")) return valueAsString.substring(1); return valueAsString; }
From source file:org.eclipse.che.api.core.jsonrpc.JsonRpcUtils.java
License:Open Source License
static <T> T getAs(JsonElement element, Class<T> type) { if (type.equals(String.class)) { return cast(element.getAsString()); } else if (type.equals(Double.class)) { return cast(element.getAsDouble()); } else if (type.equals(Boolean.class)) { return cast(element.getAsBoolean()); } else if (type.equals(Void.class)) { return null; } else {/*from w ww . j av a2 s .c om*/ return DtoFactory.getInstance().createDtoFromJson(element.toString(), type); } }
From source file:org.eclipse.scada.base.json.VariantJsonDeserializer.java
License:Open Source License
@Override public Variant deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; }// w ww .ja v a 2 s .c o m if (json instanceof JsonPrimitive) { return decodeFromPrimitive(json); } if (json instanceof JsonObject) { final JsonObject jsonObj = (JsonObject) json; final JsonElement type = jsonObj.get(VariantJson.FIELD_TYPE); final JsonElement value = jsonObj.get(VariantJson.FIELD_VALUE); if (type == null || type.isJsonNull()) { if (value == null) { throw new JsonParseException(String.format("Variant encoded as object must have a field '%s'", VariantJson.FIELD_VALUE)); } return Variant.valueOf(value.getAsString()); } if (!type.isJsonPrimitive()) { throw new JsonParseException( String.format("Variant field '%s' must be a string containing the variant type (%s)", VariantJson.FIELD_TYPE, StringHelper.join(VariantType.values(), ", "))); } final String typeStr = type.getAsString(); if (typeStr.equals("NULL")) { return Variant.NULL; } if (value == null || value.isJsonNull()) { throw new JsonParseException(String.format( "The type '%s' does not support a null value. Use variant type NULL instead.", typeStr)); } if (value.isJsonObject() || value.isJsonArray()) { throw new JsonParseException( "The variant value must be a JSON primitive matching the type. Arrays and objects are not supported"); } switch (type.getAsString()) { case "BOOLEAN": return Variant.valueOf(value.getAsBoolean()); case "STRING": return Variant.valueOf(value.getAsString()); case "DOUBLE": return Variant.valueOf(value.getAsDouble()); case "INT32": return Variant.valueOf(value.getAsInt()); case "INT64": return Variant.valueOf(value.getAsLong()); default: throw new JsonParseException(String.format("Type '%s' is unknown (known types: %s)", StringHelper.join(VariantType.values(), ", "))); } } throw new JsonParseException("Unknown serialization of Variant type"); }
From source file:org.greenrobot.eventbus.EventBus.java
License:Apache License
private Object getValue(Method.Data data, JsonObject json) { if (data == null) return null; String id = data.getId();/*w w w .ja v a 2 s. co m*/ Class<?> clazz = data.getType(); boolean isNull = data.getNull(); JsonElement value = json == null ? new JsonNull() : json.get(id); if (!isNull && value.isJsonNull()) throw new EventBusException( "Method.Data[" + data + "], the id[" + id + "] has null value to give " + data.getType()); if (!value.isJsonNull()) { if (clazz == Boolean.class) { return value.getAsBoolean(); } else if (clazz == Integer.class) { return value.getAsInt(); } else if (clazz == Long.class) { return value.getAsLong(); } else if (clazz == Float.class) { return value.getAsFloat(); } else if (clazz == Double.class) { return value.getAsDouble(); } else if (clazz == String.class) { return value.getAsString(); } else if (clazz == Byte.class) { return value.getAsByte(); } else if (clazz == char.class) { return value.getAsCharacter(); } else { return new Gson().fromJson(value, clazz); } } return null; }