List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
From source file:com.epishie.tabs.gson.ThingDeserializer.java
License:Apache License
@Override public Thing deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("Expected json object"); }/*from w w w .jav a 2 s . co m*/ JsonObject jsonObject = json.getAsJsonObject(); if (!jsonObject.has(KIND)) { throw new JsonParseException("Expected to have \"kind\" field"); } JsonElement kindElement = jsonObject.get(KIND); if (!kindElement.isJsonPrimitive()) { throw new JsonParseException("Expected to have a primitive \"kind\" field"); } if (!jsonObject.has(DATA)) { throw new JsonParseException("Expected to have a\"data\" field"); } String kind = kindElement.getAsString(); String id = null; String name = null; if (jsonObject.has(ID)) { JsonElement idElement = jsonObject.get(ID); id = idElement.getAsString(); } if (jsonObject.has(NAME)) { JsonElement nameElement = jsonObject.get(NAME); name = nameElement.getAsString(); } Thing thing = null; switch (kind) { case Link.KIND: Link link = context.deserialize(jsonObject.get(DATA), Link.class); thing = new Thing<>(id, name, link); break; case Listing.KIND: Listing listing = context.deserialize(jsonObject.get(DATA), Listing.class); // noinspection unchecked thing = new Thing(id, name, listing); break; case Subreddit.KIND: Subreddit subreddit = context.deserialize(jsonObject.get(DATA), Subreddit.class); // noinspection unchecked thing = new Thing(id, name, subreddit); break; case Comment.KIND: Comment comment = context.deserialize(jsonObject.get(DATA), Comment.class); // noinspection unchecked thing = new Thing(id, name, comment); break; } return thing; }
From source file:com.esotericsoftware.spine.SkeletonJson.java
License:Open Source License
void readCurve(CurveTimeline timeline, int frameIndex, JsonObject valueMap) { JsonElement curve = valueMap.has("curve") ? valueMap.get("curve") : null; if (curve == null) return;// w w w . j a v a 2 s . c om if (curve.isJsonPrimitive() && curve.getAsString().equals("stepped")) timeline.setStepped(frameIndex); else if (curve.isJsonArray()) { JsonArray curveArray = curve.getAsJsonArray(); timeline.setCurve(frameIndex, curveArray.get(0).getAsFloat(), curveArray.get(1).getAsFloat(), curveArray.get(2).getAsFloat(), curveArray.get(3).getAsFloat()); } }
From source file:com.evolveum.polygon.connector.googleapps.GoogleAppsUtil.java
License:Open Source License
private static ArrayMap<String, Object> parseJson(String json) { JsonObject object = (JsonObject) new com.google.gson.JsonParser().parse(json); Set<Map.Entry<String, JsonElement>> set = object.entrySet(); Iterator<Map.Entry<String, JsonElement>> iterator = set.iterator(); ArrayMap<String, Object> map = new ArrayMap<String, Object>(); while (iterator.hasNext()) { Map.Entry<String, JsonElement> entry = iterator.next(); String key = entry.getKey(); JsonElement value = entry.getValue(); if (!value.isJsonPrimitive()) { map.put(key, parseJson(value.toString())); } else {/* w ww . ja va2 s .co m*/ map.put(key, value.getAsString()); } } return map; }
From source file:com.facebook.buck.apple.XctoolOutputParsing.java
License:Apache License
private static void dispatchEventCallback(Gson gson, JsonElement element, XctoolEventCallback eventCallback) throws JsonParseException { LOG.debug("Parsing xctool event: %s", element); if (!element.isJsonObject()) { LOG.warn("Couldn't parse JSON object from xctool event: %s", element); return;//from ww w . java 2 s . c om } JsonObject object = element.getAsJsonObject(); if (!object.has("event")) { LOG.warn("Couldn't parse JSON event from xctool event: %s", element); return; } JsonElement event = object.get("event"); if (event == null || !event.isJsonPrimitive()) { LOG.warn("Couldn't parse event field from xctool event: %s", element); return; } switch (event.getAsString()) { case "begin-ocunit": eventCallback.handleBeginOcunitEvent(gson.fromJson(element, BeginOcunitEvent.class)); break; case "end-ocunit": eventCallback.handleEndOcunitEvent(gson.fromJson(element, EndOcunitEvent.class)); break; case "begin-test-suite": eventCallback.handleBeginTestSuiteEvent(gson.fromJson(element, BeginTestSuiteEvent.class)); break; case "end-test-suite": eventCallback.handleEndTestSuiteEvent(gson.fromJson(element, EndTestSuiteEvent.class)); break; case "begin-test": eventCallback.handleBeginTestEvent(gson.fromJson(element, BeginTestEvent.class)); break; case "end-test": eventCallback.handleEndTestEvent(gson.fromJson(element, EndTestEvent.class)); break; } }
From source file:com.facebook.buck.httpserver.TracesHelper.java
License:Apache License
private static Optional<String> tryToFindCommand(JsonObject json) { JsonElement nameEl = json.get("name"); if (nameEl == null || !nameEl.isJsonPrimitive()) { return Optional.absent(); }/*w ww . j a v a 2 s. c o m*/ JsonElement argsEl = json.get("args"); if (argsEl == null || !argsEl.isJsonObject() || argsEl.getAsJsonObject().get("command_args") == null || !argsEl.getAsJsonObject().get("command_args").isJsonPrimitive()) { return Optional.absent(); } String name = nameEl.getAsString(); String commandArgs = argsEl.getAsJsonObject().get("command_args").getAsString(); String command = "buck " + name + " " + commandArgs; return Optional.of(command); }
From source file:com.facebook.buck.json.RawParser.java
License:Apache License
/** * @return One of: String, Boolean, Long, Number, List<Object>, Map<String, Object>. *//*from w w w . j a v a2s. c o m*/ @Nullable @VisibleForTesting static Object toRawTypes(JsonElement json) { // Cases are ordered from most common to least common. if (json.isJsonPrimitive()) { JsonPrimitive primitive = json.getAsJsonPrimitive(); if (primitive.isString()) { return interner.intern(primitive.getAsString()); } else if (primitive.isBoolean()) { return primitive.getAsBoolean(); } else if (primitive.isNumber()) { Number number = primitive.getAsNumber(); // Number is likely an instance of class com.google.gson.internal.LazilyParsedNumber. if (number.longValue() == number.doubleValue()) { return number.longValue(); } else { return number; } } else { throw new IllegalStateException("Unknown primitive type: " + primitive); } } else if (json.isJsonArray()) { JsonArray array = json.getAsJsonArray(); List<Object> out = Lists.newArrayListWithCapacity(array.size()); for (JsonElement item : array) { out.add(toRawTypes(item)); } return out; } else if (json.isJsonObject()) { Map<String, Object> out = new LinkedHashMap<>(json.getAsJsonObject().entrySet().size()); for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) { // On a large project, without invoking intern(), we have seen `buck targets` OOM. When this // happened, according to the .hprof file generated using -XX:+HeapDumpOnOutOfMemoryError, // 39.6% of the memory was spent on char[] objects while 14.5% was spent on Strings. // (Another 10.5% was spent on java.util.HashMap$Entry.) Introducing intern() stopped the // OOM from happening. out.put(interner.intern(entry.getKey()), toRawTypes(entry.getValue())); } return out; } else if (json.isJsonNull()) { return null; } else { throw new IllegalStateException("Unknown type: " + json); } }
From source file:com.facebook.buck.util.trace.ChromeTraceParser.java
License:Apache License
/** * Parses a Chrome trace and stops parsing once all of the specified matchers have been * satisfied. This method parses only one Chrome trace event at a time, which avoids loading the * entire trace into memory.// ww w. j av a2s . co m * @param pathToTrace is a relative path [to the ProjectFilesystem] to a Chrome trace in the * "JSON Array Format." * @param chromeTraceEventMatchers set of matchers this invocation of {@code parse()} is trying to * satisfy. Once a matcher finds a match, it will not consider any other events in the trace. * @return a {@code Map} where every matcher that found a match will have an entry whose key is * the matcher and whose value is the one returned by * {@link ChromeTraceEventMatcher#test(JsonObject, String)} without the {@link Optional} * wrapper. */ public Map<ChromeTraceEventMatcher<?>, Object> parse(Path pathToTrace, Set<ChromeTraceEventMatcher<?>> chromeTraceEventMatchers) throws IOException { Set<ChromeTraceEventMatcher<?>> unmatchedMatchers = new HashSet<>(chromeTraceEventMatchers); Preconditions.checkArgument(!unmatchedMatchers.isEmpty(), "Must specify at least one matcher"); Map<ChromeTraceEventMatcher<?>, Object> results = new HashMap<>(); try (InputStream input = projectFilesystem.newFileInputStream(pathToTrace); JsonReader jsonReader = new JsonReader(new InputStreamReader(input))) { jsonReader.beginArray(); Gson gson = new Gson(); featureSearch: while (true) { // If END_ARRAY is the next token, then there are no more elements in the array. if (jsonReader.peek().equals(JsonToken.END_ARRAY)) { break; } // Verify and extract the name property before invoking any of the matchers. JsonObject event = gson.fromJson(jsonReader, JsonObject.class); JsonElement nameEl = event.get("name"); if (nameEl == null || !nameEl.isJsonPrimitive()) { continue; } String name = nameEl.getAsString(); // Prefer Iterator to Iterable+foreach so we can use remove(). for (Iterator<ChromeTraceEventMatcher<?>> iter = unmatchedMatchers.iterator(); iter.hasNext();) { ChromeTraceEventMatcher<?> chromeTraceEventMatcher = iter.next(); Optional<?> result = chromeTraceEventMatcher.test(event, name); if (result.isPresent()) { iter.remove(); results.put(chromeTraceEventMatcher, result.get()); if (unmatchedMatchers.isEmpty()) { break featureSearch; } } } } } // We could throw if !unmatchedMatchers.isEmpty(), but that might be overbearing. return results; }
From source file:com.flipkart.android.proteus.builder.DataParsingLayoutBuilder.java
License:Apache License
public String isDataPath(JsonElement element) { if (!element.isJsonPrimitive()) { return null; }/* www . ja v a 2 s.c om*/ String attributeValue = element.getAsString(); if (attributeValue != null && !"".equals(attributeValue) && (attributeValue.charAt(0) == ProteusConstants.DATA_PREFIX || attributeValue.charAt(0) == ProteusConstants.REGEX_PREFIX)) { return attributeValue; } return null; }
From source file:com.flipkart.android.proteus.parser.ParseHelper.java
License:Apache License
public static int parseVisibility(JsonElement element) { Integer returnValue = null;//from w w w. j a v a2s. c o m if (element.isJsonPrimitive()) { String attributeValue = element.getAsString(); returnValue = sVisibilityMode.get(attributeValue); if (null == returnValue && (attributeValue.isEmpty() || FALSE.equals(attributeValue) || ProteusConstants.DATA_NULL.equals(attributeValue))) { returnValue = View.GONE; } } else if (element.isJsonNull()) { returnValue = View.GONE; } return returnValue == null ? View.VISIBLE : returnValue; }
From source file:com.flipkart.android.proteus.parser.ParseHelper.java
License:Apache License
public static int parseInvisibility(JsonElement element) { Integer returnValue = null;//from w ww .ja v a2 s.co m if (element.isJsonPrimitive()) { String attributeValue = element.getAsString(); returnValue = sVisibilityMode.get(attributeValue); if (null == returnValue && (attributeValue.isEmpty() || FALSE.equals(attributeValue) || ProteusConstants.DATA_NULL.equals(attributeValue))) { returnValue = View.VISIBLE; } } else if (element.isJsonNull()) { returnValue = View.VISIBLE; } return returnValue == null ? View.GONE : returnValue; }