List of usage examples for com.google.gson JsonElement isJsonObject
public boolean isJsonObject()
From source file:com.github.dpsm.android.print.gson.GsonResultOperator.java
License:Apache License
@Override public Subscriber<? super Response> call(final Subscriber<? super T> subscriber) { return new Subscriber<Response>() { @Override// ww w.ja va 2 s . c om public void onCompleted() { subscriber.onCompleted(); } @Override public void onError(final Throwable e) { subscriber.onError(e); } @Override public void onNext(final Response response) { switch (response.getStatus()) { case HttpURLConnection.HTTP_OK: InputStreamReader reader = null; try { reader = new InputStreamReader(response.getBody().in()); final JsonElement jsonElement = mGSON.fromJson(new JsonReader(reader), JsonObject.class); if (jsonElement != null && jsonElement.isJsonObject()) { final T result = mConstructor.newInstance(jsonElement.getAsJsonObject()); subscriber.onNext(result); } } catch (Exception e) { subscriber.onError(e); } finally { if (reader != null) { try { reader.close(); } catch (IOException e) { // Nothing to do here } } } break; default: subscriber.onError(new IOException("Http Response Failed: " + response.getStatus())); break; } } }; }
From source file:com.github.francescojo.gsondbg.GsonDebuggable.java
private void inspectJsonObject(JsonObject jsonObject, Class<?> klass) { Map<String, Field> mappingInfo = new HashMap<String, Field>(); for (Field classField : klass.getDeclaredFields()) { Annotation[] annotations = classField.getAnnotations(); if (null == annotations || 0 == annotations.length) { mappingInfo.put(classField.getName(), classField); } else {/*from w ww. j a v a 2 s . c om*/ for (Annotation annotation : annotations) { if (annotation instanceof SerializedName) { String customName = ((SerializedName) annotation).value(); mappingInfo.put(customName, classField); /* * FIXME: alternate() is introduced in Gson 2.4. Safe to delete if your Gson is lower than 2.4. */ try { String[] alternateNames = ((SerializedName) annotation).alternate(); for (String alternateName : alternateNames) { mappingInfo.put(alternateName, classField); } } catch (NoSuchMethodError ignore) { } } } } } for (Map.Entry<String, JsonElement> entry : jsonObject.entrySet()) { String key = entry.getKey(); JsonElement value = entry.getValue(); if (!mappingInfo.containsKey(key)) { /* * Gson ignores fields that are not found in json by default - following same rule in here. */ continue; } Field javaField = mappingInfo.get(key); Class<?> javaType = javaField.getType(); if (WellKnownTypeCastingRules.isWellKnown(javaType)) { if (!(value instanceof JsonPrimitive)) { log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }", javaField.getDeclaringClass().getName(), javaField.getName(), javaField.getType().getCanonicalName(), key, value); continue; } WellKnownTypeCastingRules rule = WellKnownTypeCastingRules.byJavaType(javaType); JsonPrimitive primitive = value.getAsJsonPrimitive(); if (rule.isAcceptable(primitive)) { continue; } log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }", javaField.getDeclaringClass().getName(), javaField.getName(), javaField.getType().getCanonicalName(), key, value); } else if (javaType.isArray()) { try { gson.fromJson(value, javaType); } catch (JsonSyntaxException e) { log("%s#%s is declared as ''%s''; however JSON is: { \"%s\": %s }", javaField.getDeclaringClass().getName(), javaField.getName(), javaField.getType().getCanonicalName(), key, value); } } else if (value.isJsonObject()) { inspectJsonObject(value.getAsJsonObject(), javaType); } } }
From source file:com.github.GsonPrettyPrinter.java
License:Open Source License
private List<String> toStringList(final JsonElement je) { if (je == null || je.isJsonNull()) return new ArrayList<String>(Arrays.asList(new String[] { "null" })); if (je.isJsonPrimitive()) return Collections.singletonList(je.getAsJsonPrimitive().toString()); if (je.isJsonArray()) { final JsonArray jsonArray = je.getAsJsonArray(); return arrayToStringList(jsonArray); } else if (je.isJsonObject()) { final JsonObject jsonObject = je.getAsJsonObject(); return objectToStringList(jsonObject); }//from www . j a va 2s. c o m throw new RuntimeException("Unsupported Json element: " + je.getClass().getName()); }
From source file:com.github.ithildir.airbot.server.api.ai.AirQualityApiAiFulfillmentBuilder.java
License:Open Source License
private String _getLocationString(AIResponse aiResponse) { Result result = aiResponse.getResult(); Map<String, JsonElement> parameters = result.getParameters(); JsonElement jsonElement = parameters.get("location"); if ((jsonElement == null) || !jsonElement.isJsonObject()) { return null; }//from www .j a va 2 s.c o m JsonObject jsonObject = jsonElement.getAsJsonObject(); jsonElement = jsonObject.get("business-name"); if (jsonElement == null) { jsonElement = jsonObject.get("city"); } return jsonElement.getAsString(); }
From source file:com.github.jramos.snowplow.operators.MobileContextExtractionOp.java
License:Apache License
@Override public SnowplowEventModel apply(SnowplowEventModel event) { String context = event.getContexts(); try {/*from w w w.j a va2s . c om*/ String platform = event.getPlatform(); if (platform.equals(SnowplowPlatform.Mobile.toString())) { // minimal tablet vs mobile detection if (isTablet(event.getUseragent())) { event.setDvce_type(SnowplowDeviceType.Tablet.toString()); event.setDvce_ismobile(Boolean.FALSE); } else { event.setDvce_type(SnowplowDeviceType.Mobile.toString()); event.setDvce_ismobile(Boolean.TRUE); } JsonObject rootObj = parser.parse(context).getAsJsonObject(); if (rootObj.has(JSON_DATA)) { JsonArray dataArray = rootObj.getAsJsonArray(JSON_DATA); // find the correct object by matching on the schema JsonObject mobileContextObject = null; for (int i = 0; i < dataArray.size(); i++) { JsonElement element = dataArray.get(i); if (element.isJsonObject()) { JsonObject jsonObject = element.getAsJsonObject(); if (jsonObject.has(JSON_SCHEMA)) { String schema = jsonObject.getAsJsonPrimitive(JSON_SCHEMA).getAsString(); if (schema.contains(SCHEMA_TAG)) { mobileContextObject = jsonObject; break; } } } } // parse out the mobile fields we want if (mobileContextObject != null && mobileContextObject.has(JSON_DATA)) { JsonObject dataObject = mobileContextObject.getAsJsonObject(JSON_DATA); if (dataObject.has(JSON_OPEN_IDFA)) { // use as cross device user id - i.e network user id String openIDFA = dataObject.getAsJsonPrimitive(JSON_OPEN_IDFA).getAsString(); event.setNetwork_userid(openIDFA); } String deviceManufacturer = dataObject.getAsJsonPrimitive(JSON_DEVICE_MANUFACTURER) .getAsString(); event.setOs_manufacturer(deviceManufacturer); String osType = dataObject.getAsJsonPrimitive(JSON_OS_TYPE).getAsString(); event.setOs_family(osType); String osVersion = dataObject.getAsJsonPrimitive(JSON_OS_VERSION).getAsString(); String deviceModel = dataObject.getAsJsonPrimitive(JSON_DEVICE_MODEL).getAsString(); osNameBuffer.setLength(0); osNameBuffer.append(osType).append(" ").append(osVersion); if (deviceModel != null && deviceModel.trim().length() > 0) { osNameBuffer.append(" (").append(deviceModel.trim()).append(")"); } event.setOs_name(osNameBuffer.toString()); } } } } catch (Exception e) { LOG.error("Exception applying operator to mobile context " + context, e); } return event; }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
License:Apache License
@SuppressWarnings("unchecked") private Map<String, Object> createDocument(JsonElement documentElement) { if (documentElement.isJsonObject()) { JsonObject documentObject = documentElement.getAsJsonObject(); return (Map<String, Object>) gson.fromJson(documentObject, Map.class); }/*from w w w . j ava2 s.c om*/ return new HashMap<String, Object>(); }
From source file:com.github.maoo.indexer.client.WebScriptsAlfrescoClient.java
License:Apache License
private List<AlfrescoUser> usersFromHttpEntity(HttpEntity entity) throws IOException { Reader entityReader = new InputStreamReader(entity.getContent()); JsonElement responseObject = gson.fromJson(entityReader, JsonElement.class); if (!responseObject.isJsonArray()) { throw new AlfrescoParseException("Users must be a json array."); }//from www . j av a2s.c om List<AlfrescoUser> users = new ArrayList<AlfrescoUser>(); JsonArray usersArray = responseObject.getAsJsonArray(); for (JsonElement userElement : usersArray) { if (!userElement.isJsonObject()) { throw new AlfrescoParseException("User must be a json object."); } AlfrescoUser user = getUser(userElement.getAsJsonObject()); users.add(user); } return users; }
From source file:com.github.rustdt.tooling.RustJsonMessageParser.java
License:Open Source License
protected ArrayList2<String> parseNotes(JsonElement children) throws CommonException { ArrayList2<String> notes = new ArrayList2<>(); if (children == null || !children.isJsonArray()) { return notes; }/*from ww w .j ava2 s . co m*/ JsonArray childrenArray = children.getAsJsonArray(); if (childrenArray.size() == 0) { return notes; } for (JsonElement child : childrenArray) { if (child.isJsonObject()) { String childMessageString = helper.getOptionalString(child.getAsJsonObject(), "message"); if (childMessageString != null && !childMessageString.isEmpty()) { notes.add(childMessageString); } } } return notes; }
From source file:com.github.strawberry.util.Json.java
License:Open Source License
public static Collection parseArray(String json) { JsonArray o = (JsonArray) parser.parse(json); Collection c = Lists.newArrayList(); for (JsonElement value : o) { if (!value.isJsonPrimitive()) { if (value.isJsonArray()) { c.add(parseArray(value.toString())); } else if (value.isJsonObject()) { c.add(parse(value.toString())); }/*from w w w.j a v a 2 s . c o m*/ } else { c.add(parsePrimitive(value)); } } return c; }
From source file:com.github.strawberry.util.Json.java
License:Open Source License
public static Map<String, Object> parse(String json) { JsonObject o = (JsonObject) parser.parse(json); Set<Map.Entry<String, JsonElement>> set = o.entrySet(); Map<String, Object> map = Maps.newHashMap(); for (Map.Entry<String, JsonElement> e : set) { String key = e.getKey();//from w w w.j av a2 s. c o m JsonElement value = e.getValue(); if (!value.isJsonPrimitive()) { if (value.isJsonObject()) { map.put(key, parse(value.toString())); } else if (value.isJsonArray()) { map.put(key, parseArray(value.toString())); } } else { map.put(key, parsePrimitive(value)); } } return map; }