List of usage examples for com.google.gson JsonPrimitive getAsBigDecimal
@Override
public BigDecimal getAsBigDecimal()
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//from ww w . j a va 2 s . c o m * @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.cloudbase.CBNaturalDeserializer.java
License:Open Source License
private Object handlePrimitive(JsonPrimitive json) { if (json.isBoolean()) return json.getAsBoolean(); else if (json.isString()) return json.getAsString(); else {/*from ww w. j av a2 s .co m*/ BigDecimal bigDec = json.getAsBigDecimal(); // Find out if it is an int type try { bigDec.toBigIntegerExact(); try { return bigDec.intValueExact(); } catch (ArithmeticException e) { } return bigDec.longValue(); } catch (ArithmeticException e) { } // Just return it as a double return bigDec.doubleValue(); } }
From source file:com.getperka.flatpack.codexes.DynamicCodex.java
License:Apache License
/** * Attempt to infer the type from the JsonElement presented. * <ul>// w w w .ja v a 2s . co m * <li>boolean -> {@link Boolean} * <li>number -> {@link BigDecimal} * <li>string -> {@link HasUuid} or {@link String} * <li>array -> {@link ListCodex} * <li>object -> {@link StringMapCodex} * </ul> */ @Override public Object readNotNull(JsonElement element, DeserializationContext context) throws Exception { if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { // Always return numbers as BigDecimals for consistency return primitive.getAsBigDecimal(); } else { String value = primitive.getAsString(); // Interpret UUIDs as entity references if (UUID_PATTERN.matcher(value).matches()) { UUID uuid = UUID.fromString(value); HasUuid entity = context.getEntity(uuid); if (entity != null) { return entity; } } return value; } } else if (element.isJsonArray()) { return listCodex.get().readNotNull(element, context); } else if (element.isJsonObject()) { return mapCodex.get().readNotNull(element, context); } context.fail(new UnsupportedOperationException("Cannot infer data type for " + element.toString())); return null; }
From source file:com.jayway.jsonpath.internal.spi.mapper.GsonMapper.java
License:Apache License
@Override public Object convert(Object src, Class<?> srcType, Class<?> targetType, Configuration conf) { assertValidConversion(src, srcType, targetType); if (src == null || src.getClass().equals(JsonNull.class)) { return null; }//w w w . ja va 2 s . c o m if (JsonPrimitive.class.isAssignableFrom(srcType)) { JsonPrimitive primitive = (JsonPrimitive) src; if (targetType.equals(Long.class)) { return primitive.getAsLong(); } else if (targetType.equals(Integer.class)) { return primitive.getAsInt(); } else if (targetType.equals(BigInteger.class)) { return primitive.getAsBigInteger(); } else if (targetType.equals(Byte.class)) { return primitive.getAsByte(); } else if (targetType.equals(BigDecimal.class)) { return primitive.getAsBigDecimal(); } else if (targetType.equals(Double.class)) { return primitive.getAsDouble(); } else if (targetType.equals(Float.class)) { return primitive.getAsFloat(); } else if (targetType.equals(String.class)) { return primitive.getAsString(); } else if (targetType.equals(Boolean.class)) { return primitive.getAsBoolean(); } else if (targetType.equals(Date.class)) { if (primitive.isNumber()) { return new Date(primitive.getAsLong()); } else if (primitive.isString()) { try { return DateFormat.getInstance().parse(primitive.getAsString()); } catch (ParseException e) { throw new MappingException(e); } } } } else if (JsonObject.class.isAssignableFrom(srcType)) { JsonObject srcObject = (JsonObject) src; if (targetType.equals(Map.class)) { Map<String, Object> targetMap = new LinkedHashMap<String, Object>(); for (Map.Entry<String, JsonElement> entry : srcObject.entrySet()) { Object val = null; JsonElement element = entry.getValue(); if (element.isJsonPrimitive()) { val = GsonJsonProvider.unwrap(element); } else if (element.isJsonArray()) { val = convert(element, element.getClass(), List.class, conf); } else if (element.isJsonObject()) { val = convert(element, element.getClass(), Map.class, conf); } else if (element.isJsonNull()) { val = null; } targetMap.put(entry.getKey(), val); } return targetMap; } } else if (JsonArray.class.isAssignableFrom(srcType)) { JsonArray srcArray = (JsonArray) src; if (targetType.equals(List.class)) { List<Object> targetList = new ArrayList<Object>(); for (JsonElement element : srcArray) { if (element.isJsonPrimitive()) { targetList.add(GsonJsonProvider.unwrap(element)); } else if (element.isJsonArray()) { targetList.add(convert(element, element.getClass(), List.class, conf)); } else if (element.isJsonObject()) { targetList.add(convert(element, element.getClass(), Map.class, conf)); } else if (element.isJsonNull()) { targetList.add(null); } } return targetList; } } throw new MappingException("Can not map: " + srcType.getName() + " to: " + targetType.getName()); }
From source file:com.vmware.xenon.common.serialization.ObjectCollectionTypeConverter.java
License:Open Source License
@Override public Collection<Object> deserialize(JsonElement json, Type type, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonArray()) { throw new JsonParseException("Expecting a json array object but found: " + json); }//w w w. j a v a 2 s. c om Collection<Object> result; if (TYPE_SET.equals(type)) { result = new HashSet<>(); } else if (TYPE_LIST.equals(type) || TYPE_COLLECTION.equals(type)) { result = new LinkedList<>(); } else { throw new JsonParseException("Unexpected target type: " + type); } JsonArray jsonArray = json.getAsJsonArray(); for (JsonElement entry : jsonArray) { if (entry.isJsonNull()) { result.add(null); } else if (entry.isJsonPrimitive()) { JsonPrimitive elem = entry.getAsJsonPrimitive(); Object value = null; if (elem.isBoolean()) { value = elem.getAsBoolean(); } else if (elem.isString()) { value = elem.getAsString(); } else if (elem.isNumber()) { // We don't know if this is an integer, long, float or double... BigDecimal num = elem.getAsBigDecimal(); try { value = num.longValueExact(); } catch (ArithmeticException e) { value = num.doubleValue(); } } else { throw new RuntimeException("Unexpected value type for json element:" + elem); } result.add(value); } else { // keep JsonElement to prevent stringified json issues result.add(entry); } } return result; }
From source file:com.vsthost.rnd.jpsolver.data.ValueBuilder.java
License:Apache License
public static Value fromJsonElement(JsonElement element) { // Check primitive types: if (element instanceof JsonNull) { // Return the NONE value: return Value.NONE; } else if (element instanceof JsonPrimitive) { // Cast and get the primitive: JsonPrimitive primitive = (JsonPrimitive) element; // Check primitive types: if (primitive.isBoolean()) { return primitive.getAsBoolean() ? BooleanValue.TRUE : BooleanValue.FALSE; } else if (primitive.isNumber()) { return new NumericValue(primitive.getAsBigDecimal()); } else {//from www . j av a 2 s . co m return new TextValue(primitive.getAsString()); } } else if (element instanceof JsonArray) { // Cast and get the array: JsonArray array = (JsonArray) element; // Iterate over the elements and populate the return value: ValueList<Value> retval = new ValueList<Value>(); for (JsonElement e : array) { retval.add(ValueBuilder.fromJsonElement(e)); } // Done, return: return retval; } else { // Cast and get the object: JsonObject object = (JsonObject) element; // Iterate over the elements and populate the return value: ValueMap retval = new ValueMap(); for (Map.Entry<String, JsonElement> e : object.entrySet()) { retval.put(e.getKey(), ValueBuilder.fromJsonElement(e.getValue())); } // Done, return: return retval; } }
From source file:com.yandex.money.api.typeadapters.JsonUtils.java
License:Open Source License
/** * Gets nullable BigDecimal from a JSON object. * * @param object json object//w w w .j av a2s . c o m * @param memberName member's name * @return {@link java.math.BigDecimal} value */ public static BigDecimal getBigDecimal(JsonObject object, String memberName) { JsonPrimitive primitive = getPrimitiveChecked(object, memberName); return primitive == null ? null : primitive.getAsBigDecimal(); }
From source file:de.csdev.ebus.cfg.std.EBusValueJsonDeserializer.java
License:Open Source License
@Override public List<EBusValueDTO> deserialize(JsonElement jElement, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonArray asJsonArray = jElement.getAsJsonArray(); ArrayList<EBusValueDTO> result = new ArrayList<EBusValueDTO>(); ArrayList<String> fields = new ArrayList<String>(); for (Field field : EBusValueDTO.class.getDeclaredFields()) { SerializedName annotation = field.getAnnotation(SerializedName.class); if (annotation != null) { fields.add(annotation.value()); } else {/*from w w w . j a v a2s. co m*/ fields.add(field.getName()); } } for (JsonElement jsonElement : asJsonArray) { JsonObject jObject = jsonElement.getAsJsonObject(); EBusValueDTO valueDTO = context.deserialize(jObject, EBusValueDTO.class); for (Entry<String, JsonElement> entry : jObject.entrySet()) { if (!fields.contains(entry.getKey())) { if (entry.getValue().isJsonPrimitive()) { JsonPrimitive primitive = (JsonPrimitive) entry.getValue(); if (primitive.isNumber()) { valueDTO.setProperty(entry.getKey(), primitive.getAsBigDecimal()); } else if (primitive.isBoolean()) { valueDTO.setProperty(entry.getKey(), primitive.getAsBoolean()); } else if (primitive.isString()) { valueDTO.setProperty(entry.getKey(), primitive.getAsString()); } } else { valueDTO.setProperty(entry.getKey(), entry.getValue().getAsString()); } } } result.add(valueDTO); } return result; }
From source file:fr.zcraft.MultipleInventories.snaphots.ItemStackSnapshot.java
License:Open Source License
/** * From a JSON element, constructs a data structure representing * the same structure (recursively) using native types. * * <p>We had to re-implement this to ensure the generated structure to have the * right data type (instead of all numbers being doubles) and precision.</p> * * @param element The json element to be decoded. * @return A native data structure (either a {@link Map Map<String, Object>}, * a {@link List List<Object>}, or a native type) representing the same * structure (recursively)./*from w w w. ja va 2 s. c om*/ * * @see #jsonToNative(JsonObject) Converts a json object to an explicit {@link Map}. * The JavaDoc also contains explainations on why this is needed. */ private static Object jsonToNative(final JsonElement element) { if (element.isJsonObject()) { return jsonToNative(element.getAsJsonObject()); } else if (element.isJsonArray()) { final List<Object> list = new ArrayList<>(); element.getAsJsonArray().forEach(listElement -> { final Object nativeValue = jsonToNative(listElement); if (nativeValue != null) { list.add(nativeValue); } }); return list; } else if (element.isJsonPrimitive()) { final JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isString()) { return primitive.getAsString(); } else /* it's a number we yet have to find the type. */ { final BigDecimal number = primitive.getAsBigDecimal(); try { return number.byteValueExact(); } catch (final ArithmeticException e1) { try { return number.shortValueExact(); } catch (final ArithmeticException e2) { try { return number.intValueExact(); } catch (final ArithmeticException e3) { try { return number.longValueExact(); } catch (final ArithmeticException e4) { try { return number.doubleValue(); } catch (final ArithmeticException | NumberFormatException e5) { return number; } } } } } } } // Else the element is null. return null; }
From source file:org.apache.hadoop.hive.json.JsonSchemaFinder.java
License:Apache License
private static HiveType pickType(JsonElement json) { if (json.isJsonPrimitive()) { JsonPrimitive prim = (JsonPrimitive) json; if (prim.isBoolean()) { return new BooleanType(); } else if (prim.isNumber()) { BigDecimal dec = prim.getAsBigDecimal(); if (dec.scale() > 0) { return new FloatingPointType(dec.doubleValue()); } else { return new IntegerType(dec.longValue()); }// w ww. j ava2 s . c om } else { String str = prim.getAsString(); if (DATE_PATTERN.matcher(str).matches()) { return new TimestampType(); } else if (HEX_PATTERN.matcher(str).matches()) { return new BinaryType(); } else { return new StringType(); } } } else if (json.isJsonNull()) { return new NullType(); } else if (json.isJsonArray()) { ListType result = new ListType(); for (JsonElement child : ((JsonArray) json)) { HiveType sub = pickType(child); if (result.elementType == null) { result.elementType = sub; } else { result.elementType = mergeType(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); } StringBuilder builder = new StringBuilder(); boolean first = true; for (String key : result.fields.keySet()) { if (first) { first = false; } else { builder.append(","); } builder.append(key); } result.values.add(builder.toString()); return result; } }