Java Code Examples for com.google.gson.JsonPrimitive#isString()
The following examples show how to use
com.google.gson.JsonPrimitive#isString() .
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: MapTypeAdapterFactory.java From letv with Apache License 2.0 | 6 votes |
private String keyToString(JsonElement keyElement) { if (keyElement.isJsonPrimitive()) { JsonPrimitive primitive = keyElement.getAsJsonPrimitive(); if (primitive.isNumber()) { return String.valueOf(primitive.getAsNumber()); } if (primitive.isBoolean()) { return Boolean.toString(primitive.getAsBoolean()); } if (primitive.isString()) { return primitive.getAsString(); } throw new AssertionError(); } else if (keyElement.isJsonNull()) { return "null"; } else { throw new AssertionError(); } }
Example 2
Source File: JsonAttributeValueSerialization.java From XACML with MIT License | 6 votes |
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 3
Source File: GsonUtil.java From incubator-retired-wave with Apache License 2.0 | 6 votes |
/** * Unpack a JsonElement into the object type * * @param <T> The type to deserialize * @param object The object used to accept the pare result * @param valueObj The root of a tree of JsonElements or an indirection index * @param gson A Gson context * @param raw * @throws GsonException */ public static <T extends GsonSerializable> void extractJsonObject(T object, JsonElement valueObj, Gson gson, RawStringData raw) throws GsonException { if (valueObj.isJsonObject()) { object.fromGson(valueObj.getAsJsonObject(), gson, raw); } else if (valueObj.isJsonPrimitive()) { JsonPrimitive primitive = valueObj.getAsJsonPrimitive(); String s = null; if (raw == null || !primitive.isString()) { throw new GsonException("Decoding " + valueObj + " as object " + object.getClass() + " with no RawStringData given"); } s = raw.getString(valueObj.getAsString()); GsonUtil.parseJson(object, gson, s, raw); } else { throw new GsonException("Cannot decode valueObject " + valueObj.getClass() + " as object " + object.getClass()); } }
Example 4
Source File: MobileServiceTableBase.java From azure-mobile-apps-android-client with Apache License 2.0 | 6 votes |
/** * @return the string value represented by the object. * * @param o The object for which the string value is to be extracted */ protected String getStringValue(Object o) { String result; if (o instanceof String) { result = (String) o; } else if (o instanceof JsonElement) { JsonElement json = (JsonElement) o; if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { result = primitive.getAsString(); } else { throw new IllegalArgumentException("Object does not represent a string value."); } } else { throw new IllegalArgumentException("Object does not represent a string value."); } } else { throw new IllegalArgumentException("Object does not represent a string value."); } return result; }
Example 5
Source File: GsonUtils.java From soul with Apache License 2.0 | 6 votes |
/** * Get JsonElement class type. * * @param element the element * @return Class class */ public Class getType(final JsonElement element) { if (!element.isJsonPrimitive()) { return element.getClass(); } final JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isString()) { return String.class; } else if (primitive.isNumber()) { String numStr = primitive.getAsString(); if (numStr.contains(DOT) || numStr.contains(E) || numStr.contains("E")) { return Double.class; } return Long.class; } else if (primitive.isBoolean()) { return Boolean.class; } else { return element.getClass(); } }
Example 6
Source File: Indexes.java From java-cloudant with Apache License 2.0 | 6 votes |
/** * Utility to list indexes of a given type. * * @param type the type of index to list, null means all types * @param modelType the class to deserialize the index into * @param <T> the type of the index * @return the list of indexes of the specified type */ private <T extends Index> List<T> listIndexType(String type, Class<T> modelType) { List<T> indexesOfType = new ArrayList<T>(); Gson g = new Gson(); for (JsonElement index : indexes) { if (index.isJsonObject()) { JsonObject indexDefinition = index.getAsJsonObject(); JsonElement indexType = indexDefinition.get("type"); if (indexType != null && indexType.isJsonPrimitive()) { JsonPrimitive indexTypePrimitive = indexType.getAsJsonPrimitive(); if (type == null || (indexTypePrimitive.isString() && indexTypePrimitive .getAsString().equals(type))) { indexesOfType.add(g.fromJson(indexDefinition, modelType)); } } } } return indexesOfType; }
Example 7
Source File: ModuleRegistry.java From Wizardry with GNU Lesser General Public License v3.0 | 5 votes |
private Object getJsonValue(String key, JsonPrimitive elem) { // TODO: Move to utils if (elem.isString()) return elem.getAsString(); else if (elem.isNumber()) return elem.getAsNumber(); else if (elem.isBoolean()) return elem.getAsBoolean(); // ... TODO: Add more data types. String value = elem.getAsString(); Wizardry.LOGGER.warn("| | |_ WARNING! Using fallback as string for parameter '" + key + "' having value '" + value + "'."); return value; }
Example 8
Source File: MobileServiceTableBase.java From azure-mobile-apps-android-client with Apache License 2.0 | 5 votes |
/** * Validates if the object represents a string value. * * @param o * @return */ protected boolean isStringType(Object o) { boolean result = (o instanceof String); if (o instanceof JsonElement) { JsonElement json = (JsonElement) o; if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); result = primitive.isString(); } } return result; }
Example 9
Source File: AbstractGsonConverter.java From helper with MIT License | 5 votes |
@Override public Object unwarpPrimitive(JsonPrimitive primitive) { if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { return primitive.getAsNumber(); } else if (primitive.isString()) { return primitive.getAsString(); } else { throw new IllegalArgumentException("Unknown primitive type: " + primitive); } }
Example 10
Source File: f.java From MiBandDecompiled with Apache License 2.0 | 5 votes |
private String a(JsonElement jsonelement) { if (jsonelement.isJsonPrimitive()) { JsonPrimitive jsonprimitive = jsonelement.getAsJsonPrimitive(); if (jsonprimitive.isNumber()) { return String.valueOf(jsonprimitive.getAsNumber()); } if (jsonprimitive.isBoolean()) { return Boolean.toString(jsonprimitive.getAsBoolean()); } if (jsonprimitive.isString()) { return jsonprimitive.getAsString(); } else { throw new AssertionError(); } } if (jsonelement.isJsonNull()) { return "null"; } else { throw new AssertionError(); } }
Example 11
Source File: JsonOps.java From DataFixerUpper with MIT License | 5 votes |
@Override public <U> U convertTo(final DynamicOps<U> outOps, final JsonElement input) { if (input instanceof JsonObject) { return convertMap(outOps, input); } if (input instanceof JsonArray) { return convertList(outOps, input); } if (input instanceof JsonNull) { return outOps.empty(); } final JsonPrimitive primitive = input.getAsJsonPrimitive(); if (primitive.isString()) { return outOps.createString(primitive.getAsString()); } if (primitive.isBoolean()) { return outOps.createBoolean(primitive.getAsBoolean()); } final BigDecimal value = primitive.getAsBigDecimal(); try { final long l = value.longValueExact(); if ((byte) l == l) { return outOps.createByte((byte) l); } if ((short) l == l) { return outOps.createShort((short) l); } if ((int) l == l) { return outOps.createInt((int) l); } return outOps.createLong(l); } catch (final ArithmeticException e) { final double d = value.doubleValue(); if ((float) d == d) { return outOps.createFloat((float) d); } return outOps.createDouble(d); } }
Example 12
Source File: JsonPrettyPrinter.java From arcusplatform with Apache License 2.0 | 5 votes |
@Override public void printPrimitive(JsonPrimitive primitive) { if(primitive.isString()) { printString(primitive.getAsString()); } // TODO style by type? else { out.append(primitive.toString()); } }
Example 13
Source File: JsonParser.java From org.hl7.fhir.core with Apache License 2.0 | 5 votes |
private void parseChildPrimitiveInstance(Element context, Property property, String name, String npath, JsonElement main, JsonElement fork) throws FHIRFormatError, DefinitionException { if (main != null && !(main instanceof JsonPrimitive)) logError(line(main), col(main), npath, IssueType.INVALID, "This property must be an simple value, not a "+main.getClass().getName(), IssueSeverity.ERROR); else if (fork != null && !(fork instanceof JsonObject)) logError(line(fork), col(fork), npath, IssueType.INVALID, "This property must be an object, not a "+fork.getClass().getName(), IssueSeverity.ERROR); else { Element n = new Element(name, property).markLocation(line(main != null ? main : fork), col(main != null ? main : fork)); context.getChildren().add(n); if (main != null) { JsonPrimitive p = (JsonPrimitive) main; n.setValue(p.getAsString()); if (!n.getProperty().isChoice() && n.getType().equals("xhtml")) { try { n.setXhtml(new XhtmlParser().setValidatorMode(policy == ValidationPolicy.EVERYTHING).parse(n.getValue(), null).getDocumentElement()); } catch (Exception e) { logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing XHTML: "+e.getMessage(), IssueSeverity.ERROR); } } if (policy == ValidationPolicy.EVERYTHING) { // now we cross-check the primitive format against the stated type if (Utilities.existsInList(n.getType(), "boolean")) { if (!p.isBoolean()) logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a boolean", IssueSeverity.ERROR); } else if (Utilities.existsInList(n.getType(), "integer", "unsignedInt", "positiveInt", "decimal")) { if (!p.isNumber()) logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a number", IssueSeverity.ERROR); } else if (!p.isString()) logError(line(main), col(main), npath, IssueType.INVALID, "Error parsing JSON: the primitive value must be a string", IssueSeverity.ERROR); } } if (fork != null) { JsonObject child = (JsonObject) fork; checkObject(child, npath); parseChildren(npath, child, n, false); } } }
Example 14
Source File: OperatorGenerator.java From streamsx.topology with Apache License 2.0 | 5 votes |
/** * Generically generate annotations. * * @see OpProperties.ANNOTATIONS */ static void genericAnnotations(JsonObject op, StringBuilder sb) { JsonArray annotations = GsonUtilities.array(op, OpProperties.ANNOTATIONS); if (annotations == null) return; for (JsonElement a : annotations) { JsonObject annotation = a.getAsJsonObject(); sb.append('@'); sb.append(jstring(annotation, OpProperties.ANNOTATION_TYPE)); sb.append('('); JsonObject properties = GsonUtilities.object(annotation, OpProperties.ANNOTATION_PROPERTIES); boolean first = true; for (Entry<String, JsonElement> property : properties.entrySet()) { if (!first) sb.append(','); sb.append(property.getKey()); sb.append('='); if (property.getValue().isJsonPrimitive()) { JsonPrimitive value = property.getValue().getAsJsonPrimitive(); if (value.isString()) sb.append(SPLGenerator.stringLiteral(value.getAsString())); else sb.append(value.getAsString()); } else { SPLGenerator.value(sb, property.getValue().getAsJsonObject()); } if (first) first = false; } sb.append(')'); sb.append('\n'); } }
Example 15
Source File: ConfigurationDeserializer.java From smarthome with Eclipse Public License 2.0 | 5 votes |
private Object deserialize(JsonPrimitive primitive) { if (primitive.isString()) { return primitive.getAsString(); } else if (primitive.isNumber()) { return primitive.getAsBigDecimal(); } else if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else { throw new IllegalArgumentException("Unsupported primitive: " + primitive); } }
Example 16
Source File: QueryOptions.java From yawp with MIT License | 5 votes |
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 17
Source File: RESTUtil.java From rest-client with Apache License 2.0 | 4 votes |
/** * * @Title: jsonTree * @Description: To generate a JSON tree * @param @param e * @param @param layer * @param @param sb * @return layer * @throws */ public static void jsonTree(JsonElement e, int layer, StringBuilder sb) { if (e.isJsonNull()) { return; } if (e.isJsonPrimitive()) { return; } if (e.isJsonArray()) { JsonArray ja = e.getAsJsonArray(); if (ja.size() > 0) { jsonTree(ja.get(0), layer, sb); } return; } if (e.isJsonObject()) { String line = RESTConst.LINE; String type = RESTConst.UNKNOWN; String spaces = " "; String vertLine = "│ "; String indent = dup(layer, spaces); layer++; if (layer <= 0) { line = " "; } Set<Entry<String, JsonElement>> es = e.getAsJsonObject().entrySet(); for (Entry<String, JsonElement> en : es) { indent = dup(layer, spaces); if (layer >= 2) { indent = dup(1, spaces) + dup(layer - 1, vertLine); } sb.append(indent).append(line).append(en.getKey()).append(" ["); if (en.getValue().isJsonArray()) { type = Array.class.getSimpleName(); } else if (en.getValue().isJsonObject()) { type = Object.class.getSimpleName(); } else if (en.getValue().isJsonPrimitive()) { JsonPrimitive jp = en.getValue().getAsJsonPrimitive(); if (jp.isBoolean()) { type = Boolean.class.getSimpleName(); } else if (jp.isNumber()) { type = Number.class.getSimpleName(); } else if (jp.isString()) { type = String.class.getSimpleName(); } } else if (en.getValue().isJsonNull()) { type = null + ""; } sb.append(type.toLowerCase()).append("]").append(lines(1)); jsonTree(en.getValue(), layer, sb); } } }
Example 18
Source File: JsonTreeReader.java From gson with Apache License 2.0 | 4 votes |
@Override public JsonToken peek() throws IOException { if (stackSize == 0) { return JsonToken.END_DOCUMENT; } Object o = peekStack(); if (o instanceof Iterator) { boolean isObject = stack[stackSize - 2] instanceof JsonObject; Iterator<?> iterator = (Iterator<?>) o; if (iterator.hasNext()) { if (isObject) { return JsonToken.NAME; } else { push(iterator.next()); return peek(); } } else { return isObject ? JsonToken.END_OBJECT : JsonToken.END_ARRAY; } } else if (o instanceof JsonObject) { return JsonToken.BEGIN_OBJECT; } else if (o instanceof JsonArray) { return JsonToken.BEGIN_ARRAY; } else if (o instanceof JsonPrimitive) { JsonPrimitive primitive = (JsonPrimitive) o; if (primitive.isString()) { return JsonToken.STRING; } else if (primitive.isBoolean()) { return JsonToken.BOOLEAN; } else if (primitive.isNumber()) { return JsonToken.NUMBER; } else { throw new AssertionError(); } } else if (o instanceof JsonNull) { return JsonToken.NULL; } else if (o == SENTINEL_CLOSED) { throw new IllegalStateException("JsonReader is closed"); } else { throw new AssertionError(); } }
Example 19
Source File: DataUtil.java From Prism with MIT License | 4 votes |
/** * Attempts to convert a JsonElement to an a known type. * * @param element JsonElement * @return Optional<Object> */ private static Optional<Object> jsonElementToObject(JsonElement element) { if (element.isJsonArray()) { List<Object> list = Lists.newArrayList(); JsonArray jsonArray = element.getAsJsonArray(); jsonArray.forEach(entry -> jsonElementToObject(entry).ifPresent(list::add)); return Optional.of(list); } else if (element.isJsonObject()) { JsonObject jsonObject = element.getAsJsonObject(); PrimitiveArray primitiveArray = PrimitiveArray.of(jsonObject); if (primitiveArray != null) { return Optional.of(primitiveArray.getArray()); } return Optional.of(dataViewFromJson(jsonObject)); } else if (element.isJsonPrimitive()) { JsonPrimitive jsonPrimitive = element.getAsJsonPrimitive(); if (jsonPrimitive.isBoolean()) { return Optional.of(jsonPrimitive.getAsBoolean()); } else if (jsonPrimitive.isNumber()) { Number number = NumberUtils.createNumber(jsonPrimitive.getAsString()); if (number instanceof Byte) { return Optional.of(number.byteValue()); } else if (number instanceof Double) { return Optional.of(number.doubleValue()); } else if (number instanceof Float) { return Optional.of(number.floatValue()); } else if (number instanceof Integer) { return Optional.of(number.intValue()); } else if (number instanceof Long) { return Optional.of(number.longValue()); } else if (number instanceof Short) { return Optional.of(number.shortValue()); } } else if (jsonPrimitive.isString()) { return Optional.of(jsonPrimitive.getAsString()); } } return Optional.empty(); }
Example 20
Source File: SNodeGson.java From swellrt with Apache License 2.0 | 3 votes |
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"); }