List of usage examples for com.google.gson JsonElement getAsJsonPrimitive
public JsonPrimitive getAsJsonPrimitive()
From source file:org.openqa.selenium.remote.JsonToBeanConverter.java
License:Apache License
@SuppressWarnings("unchecked") private <T> T convert(Class<T> clazz, Object source, int depth) { if (source == null || source instanceof JsonNull) { return null; }// w ww. jav a 2 s .c o m if (source instanceof JsonElement) { JsonElement json = (JsonElement) source; if (json.isJsonPrimitive()) { JsonPrimitive jp = json.getAsJsonPrimitive(); if (String.class.equals(clazz)) { return (T) jp.getAsString(); } if (jp.isNumber()) { if (Integer.class.isAssignableFrom(clazz) || int.class.equals(clazz)) { return (T) Integer.valueOf(jp.getAsNumber().intValue()); } else if (Long.class.isAssignableFrom(clazz) || long.class.equals(clazz)) { return (T) Long.valueOf(jp.getAsNumber().longValue()); } else if (Float.class.isAssignableFrom(clazz) || float.class.equals(clazz)) { return (T) Float.valueOf(jp.getAsNumber().floatValue()); } else if (Double.class.isAssignableFrom(clazz) || double.class.equals(clazz)) { return (T) Double.valueOf(jp.getAsNumber().doubleValue()); } else { return (T) convertJsonPrimitive(jp); } } } } if (isPrimitive(source.getClass())) { return (T) source; } if (isEnum(clazz, source)) { return (T) convertEnum(clazz, source); } if ("".equals(String.valueOf(source))) { return (T) source; } if (Command.class.equals(clazz)) { JsonObject json = new JsonParser().parse((String) source).getAsJsonObject(); SessionId sessionId = null; if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { sessionId = convert(SessionId.class, json.get("sessionId"), depth + 1); } String name = json.get("name").getAsString(); if (json.has("parameters")) { Map<String, ?> args = (Map<String, ?>) convert(HashMap.class, json.get("parameters"), depth + 1); return (T) new Command(sessionId, name, args); } return (T) new Command(sessionId, name); } if (Response.class.equals(clazz)) { Response response = new Response(); JsonObject json = source instanceof JsonObject ? (JsonObject) source : new JsonParser().parse((String) source).getAsJsonObject(); if (json.has("error") && !json.get("error").isJsonNull()) { String state = json.get("error").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); response.setValue(convert(Object.class, json.get("message"))); } if (json.has("state") && !json.get("state").isJsonNull()) { String state = json.get("state").getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } if (json.has("status") && !json.get("status").isJsonNull()) { JsonElement status = json.get("status"); if (status.getAsJsonPrimitive().isString()) { String state = status.getAsString(); response.setState(state); response.setStatus(errorCodes.toStatus(state, Optional.empty())); } else { int intStatus = status.getAsInt(); response.setState(errorCodes.toState(intStatus)); response.setStatus(intStatus); } } if (json.has("sessionId") && !json.get("sessionId").isJsonNull()) { response.setSessionId(json.get("sessionId").getAsString()); } if (json.has("value")) { response.setValue(convert(Object.class, json.get("value"))); } else { response.setValue(convert(Object.class, json)); } return (T) response; } if (SessionId.class.equals(clazz)) { // Stupid heuristic to tell if we are dealing with a selenium 2 or 3 session id. JsonElement json = source instanceof String ? new JsonParser().parse((String) source).getAsJsonObject() : (JsonElement) source; if (json.isJsonPrimitive()) { return (T) new SessionId(json.getAsString()); } return (T) new SessionId(json.getAsJsonObject().get("value").getAsString()); } if (Capabilities.class.isAssignableFrom(clazz)) { JsonObject json = source instanceof JsonElement ? ((JsonElement) source).getAsJsonObject() : new JsonParser().parse(source.toString()).getAsJsonObject(); Map<String, Object> map = convertMap(json.getAsJsonObject(), depth); return (T) new DesiredCapabilities(map); } if (Date.class.equals(clazz)) { return (T) new Date(Long.valueOf(String.valueOf(source))); } if (source instanceof String && !((String) source).startsWith("{") && Object.class.equals(clazz)) { return (T) source; } Method fromJson = getMethod(clazz, "fromJson"); if (fromJson != null) { try { return (T) fromJson.invoke(null, source.toString()); } catch (IllegalArgumentException e) { throw new WebDriverException(e); } catch (IllegalAccessException e) { throw new WebDriverException(e); } catch (InvocationTargetException e) { throw new WebDriverException(e); } } if (depth == 0) { if (source instanceof String) { source = new JsonParser().parse((String) source); } } if (source instanceof JsonElement) { JsonElement element = (JsonElement) source; if (element.isJsonNull()) { return null; } if (element.isJsonPrimitive()) { return (T) convertJsonPrimitive(element.getAsJsonPrimitive()); } if (element.isJsonArray()) { return (T) convertList(element.getAsJsonArray(), depth); } if (element.isJsonObject()) { if (Map.class.isAssignableFrom(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } if (Object.class.equals(clazz)) { return (T) convertMap(element.getAsJsonObject(), depth); } return convertBean(clazz, element.getAsJsonObject(), depth); } } return (T) source; // Crap shoot here; probably a string. }
From source file:org.openqa.selenium.remote.JsonToBeanConverter.java
License:Apache License
private Object convertJsonPrimitive(JsonElement json) { return convertJsonPrimitive(json.getAsJsonPrimitive()); }
From source file:org.pascani.dsl.dbmapper.typeadapters.UUIDDeserializer.java
License:Open Source License
@Override public UUID deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { return UUID.fromString(json.getAsJsonPrimitive().getAsString()); }
From source file:org.plos.crepo.model.metadata.RepoMetadata.java
License:Open Source License
@VisibleForTesting static Object convertJsonToImmutable(JsonElement element) { if (element.isJsonNull()) { return null; }/* ww w . j av a2 s . c om*/ if (element.isJsonPrimitive()) { JsonPrimitive primitive = element.getAsJsonPrimitive(); if (primitive.isString()) return primitive.getAsString(); if (primitive.isNumber()) return asNumber(primitive); if (primitive.isBoolean()) return primitive.getAsBoolean(); throw new RuntimeException("JsonPrimitive is not one of the expected primitive types"); } if (element.isJsonArray()) { JsonArray array = element.getAsJsonArray(); if (array.size() == 0) return Collections.emptyList(); List<Object> convertedList = new ArrayList<>(array.size()); for (JsonElement arrayElement : array) { Object convertedElement = convertJsonToImmutable(arrayElement); convertedList.add(convertedElement); } return Collections.unmodifiableList(convertedList); } if (element.isJsonObject()) { Set<Map.Entry<String, JsonElement>> entries = element.getAsJsonObject().entrySet(); if (entries.size() == 0) return Collections.emptyMap(); Map<String, Object> convertedMap = Maps.newHashMapWithExpectedSize(entries.size()); for (Map.Entry<String, JsonElement> entry : entries) { String key = Preconditions.checkNotNull(entry.getKey()); Object value = convertJsonToImmutable(entry.getValue()); convertedMap.put(key, value); } return Collections.unmodifiableMap(convertedMap); } throw new RuntimeException("JsonElement is not one of the expected subtypes"); }
From source file:org.ppojo.data.ArtifactSerializer.java
License:Apache License
private String readStringProperty(JsonElement json, String artifact_name, String propertyName, boolean isRequired, String defaultValue) { JsonElement typeElement = json.getAsJsonObject().get(propertyName); if (typeElement == null) if (isRequired) throw new RequiredPropertyMissing("Required property " + propertyName + " is missing in artifact " + artifact_name + " declaration in " + getDeserializeFilePath()); else/*from www . j a v a2s. co m*/ return defaultValue; if (!typeElement.isJsonPrimitive() || !typeElement.getAsJsonPrimitive().isString()) throw new JsonParseException("Invalid element type for property: " + propertyName + " in artifact " + artifact_name + ", expected String got " + JsonElementTypes.getType(typeElement) + ", in " + getDeserializeFilePath()); return typeElement.getAsString(); }
From source file:org.ppojo.data.CopyStyleDataSerializer.java
License:Apache License
private CopyStyleData ParseStyleJsonObject(JsonObject asObject, int memberIndex) { CopyStyleData copyStyleData = new CopyStyleData(); JsonElement styleMember = null; JsonElement methodNameMember = null; for (Map.Entry<String, JsonElement> elementEntry : asObject.entrySet()) { switch (elementEntry.getKey()) { case "style": styleMember = elementEntry.getValue(); break; case "methodName": methodNameMember = elementEntry.getValue(); break; default://from w ww . j ava 2 s . com throw new JsonParseException("Invalid member for array element pojoCopyStyles[" + memberIndex + "], unsupported field " + elementEntry.getKey() + ". Only supports fields style and methodName, in " + getDeserializeFilePath()); } } if (styleMember == null) throw new JsonParseException("Invalid element in option pojoCopyStyles[" + memberIndex + "], required field: style is missing, in " + getDeserializeFilePath()); if (!(styleMember.isJsonPrimitive() && styleMember.getAsJsonPrimitive().isString())) throw new JsonParseException("Invalid element type for option pojoCopyStyles[" + memberIndex + "] style field, expected String got " + JsonElementTypes.getType(styleMember) + ", in " + getDeserializeFilePath()); if (methodNameMember != null && !(methodNameMember.isJsonPrimitive() && methodNameMember.getAsJsonPrimitive().isString())) throw new JsonParseException("Invalid element type for option pojoCopyStyles[" + memberIndex + "] methodName field, expected String got " + JsonElementTypes.getType(methodNameMember) + ", in " + getDeserializeFilePath()); copyStyleData.style = parseStyleType(styleMember.getAsString(), memberIndex); if (methodNameMember != null) copyStyleData.methodName = EmptyIfNull(methodNameMember.getAsString()); return copyStyleData; }
From source file:org.ppojo.data.JsonElementTypes.java
License:Apache License
public static JsonElementTypes getType(JsonElement json) { if (json.isJsonObject()) return JsonElementTypes.JsonObject; if (json.isJsonArray()) return JsonElementTypes.JsonArray; if (json.isJsonNull()) return JsonElementTypes.JsonNull; if (json.isJsonPrimitive()) { JsonPrimitive jsonPrimitive = json.getAsJsonPrimitive(); if (jsonPrimitive.isBoolean()) return JsonElementTypes.Boolean; if (jsonPrimitive.isNumber()) return JsonElementTypes.Number; if (jsonPrimitive.isString()) return JsonElementTypes.String; }//w ww .j av a2 s . c om return JsonElementTypes.Unknown; }
From source file:org.qcert.camp.translator.Rule2CAMP.java
License:Open Source License
/** * Make a single data object given its type and a JsonObject containing its attributes * @param type the type/*from www.jav a2 s. c o m*/ * @param attributes the attributes * @return the constructed object instance * @throws Exception */ private static Object makeDataObject(String type, JsonObject attributes) throws Exception { Object ans = Class.forName(type).newInstance(); for (Entry<String, JsonElement> attribute : attributes.entrySet()) { JsonElement value = attribute.getValue(); if (value.isJsonPrimitive()) setAttribute(ans, attribute.getKey(), valueFromJson(value.getAsJsonPrimitive())); else if (value.isJsonArray()) { JsonArray array = value.getAsJsonArray(); List<Object> collection = new ArrayList<>(); setAttribute(ans, attribute.getKey(), collection); for (JsonElement element : array) { if (element.isJsonPrimitive()) collection.add(valueFromJson((element.getAsJsonPrimitive()))); else throw new UnsupportedOperationException( "Only handling collections of primitive type at this time"); } } } return ans; }
From source file:org.qcert.runtime.DataComparator.java
License:Apache License
private static DType getType(JsonElement obj) { if (obj == null) { return DType.DT_JNULL; } else if (obj.isJsonNull()) { return DType.DT_NULL; } else if (obj.isJsonPrimitive()) { final JsonPrimitive prim = obj.getAsJsonPrimitive(); if (prim.isBoolean()) { return DType.DT_BOOL; } else if (prim.isString()) { return DType.DT_STRING; } else if (prim.isNumber()) { final Number num = prim.getAsNumber(); if (num instanceof LazilyParsedNumber) { return DType.DT_LAZYNUM; } else if (num instanceof Long || num instanceof Short || num instanceof Integer) { return DType.DT_LONG; } else if (num instanceof Double || num instanceof Short || num instanceof Float) { return DType.DT_DOUBLE; } else { throw new RuntimeException( "Unknown primitive json number type: " + num + " of type " + num.getClass()); }/*from w w w . ja va2 s .c o m*/ } else { throw new RuntimeException("Unknown primitive json type: " + prim); } } else if (obj.isJsonArray()) { return DType.DT_COLL; } else if (obj.isJsonObject()) { return DType.DT_REC; } else { throw new RuntimeException("Unknown json type: " + obj + " of type " + obj.getClass()); } }
From source file:org.qcert.runtime.UnaryOperators.java
License:Apache License
private static void tostring(StringBuilder sb, JsonElement e) { if (e == null || e.isJsonNull()) { sb.append("null"); } else if (e.isJsonPrimitive()) { tostring(sb, e.getAsJsonPrimitive()); } else if (e.isJsonArray()) { tostring(sb, e.getAsJsonArray()); } else if (e.isJsonObject()) { tostring(sb, e.getAsJsonObject()); } else {/*from w w w. j a v a 2 s . c o m*/ sb.append(e.toString()); } }