List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
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 www .j av a 2 s .co 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; }
From source file:com.github.zhizheng.json.JsonValueTypes.java
License:Apache License
/** * Json /*from w w w . j a va 2 s . co m*/ * * @param jsonElement * @return */ public static String getJsonValueType(JsonElement jsonElement) { if (jsonElement.isJsonObject()) { return OBJECT.toString(); } if (jsonElement.isJsonArray()) { return ARRAY.toString(); } if (jsonElement.isJsonPrimitive()) { JsonPrimitive asJsonPrimitive = jsonElement.getAsJsonPrimitive(); if (asJsonPrimitive.isBoolean()) { return BOOLEAN.toString(); } if (asJsonPrimitive.isNumber()) { return NUMBER.toString(); } return STRING.toString(); } return NULL.toString(); }
From source file:com.google.dart.server.internal.remote.RemoteAnalysisServerImpl.java
License:Open Source License
/** * Attempts to handle the given {@link JsonObject} as a notification. Return {@code true} if it * was handled, otherwise {@code false} is returned. * * @return {@code true} if it was handled, otherwise {@code false} is returned *//*w w w . j a v a2 s .c o m*/ private boolean processNotification(JsonObject response) throws Exception { // prepare notification kind JsonElement eventElement = response.get("event"); if (eventElement == null || !eventElement.isJsonPrimitive()) { return false; } String event = eventElement.getAsString(); // handle each supported notification kind if (event.equals(ANALYSIS_NOTIFICATION_ERRORS)) { // analysis.errors new NotificationAnalysisErrorsProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_FLUSH_RESULTS)) { // analysis.flushResults new NotificationAnalysisFlushResultsProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_HIGHTLIGHTS)) { // analysis.highlights new NotificationAnalysisHighlightsProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_IMPLEMENTED)) { // analysis.implemented new NotificationAnalysisImplementedProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_NAVIGATION)) { // analysis.navigation new NotificationAnalysisNavigationProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_OCCURRENCES)) { // analysis.occurrences new NotificationAnalysisOccurrencesProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_OUTLINE)) { // analysis.outline new NotificationAnalysisOutlineProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_OVERRIDES)) { // analysis.overrides new NotificationAnalysisOverridesProcessor(listener).process(response); } else if (event.equals(ANALYSIS_NOTIFICATION_ANALYZED_FILES)) { // analysis.errors new NotificationAnalysisAnalyzedFilesProcessor(listener).process(response); } else if (event.equals(COMPLETION_NOTIFICATION_RESULTS)) { // completion.results new NotificationCompletionResultsProcessor(listener).process(response); } else if (event.equals(SEARCH_NOTIFICATION_RESULTS)) { // search.results new NotificationSearchResultsProcessor(listener).process(response); } else if (event.equals(SERVER_NOTIFICATION_STATUS)) { // server.status new NotificationServerStatusProcessor(listener).process(response); } else if (event.equals(SERVER_NOTIFICATION_ERROR)) { // server.error new NotificationServerErrorProcessor(listener).process(response); } else if (event.equals(SERVER_NOTIFICATION_CONNECTED)) { // server.connected new NotificationServerConnectedProcessor(listener).process(response); } else if (event.equals(LAUNCH_DATA_NOTIFICATION_RESULTS)) { new NotificationExecutionLaunchDataProcessor(listener).process(response); } // it is a notification, even if we did not handle it return true; }
From source file:com.google.gerrit.httpd.TokenVerifiedRestApiServlet.java
License:Apache License
private static ParsedBody parseJson(HttpServletRequest req, HttpServletResponse res) throws IOException { try {// w w w. j a va 2s.c o m JsonElement element = new JsonParser().parse(req.getReader()); if (!element.isJsonObject()) { sendError(res, SC_BAD_REQUEST, "Expected JSON object in request body"); return null; } ParsedBody body = new ParsedBody(); body.req = req; body.json = (JsonObject) element; JsonElement authKey = body.json.remove(AUTHKEY_NAME); if (authKey != null && authKey.isJsonPrimitive() && authKey.getAsJsonPrimitive().isString()) { body._authkey = authKey.getAsString(); } return body; } catch (JsonParseException e) { sendError(res, SC_BAD_REQUEST, "Invalid JSON object in request body"); return null; } }
From source file:com.google.gerrit.server.events.EventDeserializer.java
License:Apache License
@Override public Event deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { if (!json.isJsonObject()) { throw new JsonParseException("Not an object"); }/*from w ww. j ava 2s. c o m*/ JsonElement typeJson = json.getAsJsonObject().get("type"); if (typeJson == null || !typeJson.isJsonPrimitive() || !typeJson.getAsJsonPrimitive().isString()) { throw new JsonParseException("Type is not a string: " + typeJson); } String type = typeJson.getAsJsonPrimitive().getAsString(); Class<?> cls = EventTypes.getClass(type); if (cls == null) { throw new JsonParseException("Unknown event type: " + type); } return context.deserialize(json, cls); }
From source file:com.google.gwtjsonrpc.server.CallDeserializer.java
License:Apache License
private static boolean isString(final JsonElement e) { return e != null && e.isJsonPrimitive() && e.getAsJsonPrimitive().isString(); }
From source file:com.google.gwtjsonrpc.server.SqlDateDeserializer.java
License:Apache License
public java.sql.Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; }// w w w . j ava 2 s . c om if (!json.isJsonPrimitive()) { throw new JsonParseException("Expected string for date type"); } final JsonPrimitive p = (JsonPrimitive) json; if (!p.isString()) { throw new JsonParseException("Expected string for date type"); } try { return java.sql.Date.valueOf(p.getAsString()); } catch (IllegalArgumentException e) { throw new JsonParseException("Not a date string"); } }
From source file:com.google.gwtjsonrpc.server.SqlTimestampDeserializer.java
License:Apache License
public java.sql.Timestamp deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { if (json.isJsonNull()) { return null; }/* ww w. ja v a2 s. com*/ if (!json.isJsonPrimitive()) { throw new JsonParseException("Expected string for timestamp type"); } final JsonPrimitive p = (JsonPrimitive) json; if (!p.isString()) { throw new JsonParseException("Expected string for timestamp type"); } return JavaSqlTimestamp_JsonSerializer.parseTimestamp(p.getAsString()); }
From source file:com.google.iosched.model.DataExtractor.java
License:Open Source License
public JsonArray extractSessions(JsonDataSources sources) { if (videoSessionsById == null) { throw new IllegalStateException( "You need to extract video sessions before attempting to extract sessions"); }//from w w w.j a va 2 s. c om if (categoryToTagMap == null) { throw new IllegalStateException("You need to extract tags before attempting to extract sessions"); } JsonArray result = new JsonArray(); JsonDataSource source = sources.getSource(VendorAPISource.MainTypes.topics.name()); if (source != null) { for (JsonObject origin : source) { if (isVideoSession(origin)) { // Sessions with the Video tag are processed as video library content continue; } if (isHiddenSession(origin)) { // Sessions with a "Hidden from schedule" flag should be ignored continue; } JsonElement title = get(origin, VendorAPISource.Topics.title); // Since the CMS returns an empty keynote as a session, we need to ignore it if (title != null && title.isJsonPrimitive() && "keynote".equalsIgnoreCase(title.getAsString())) { continue; } JsonObject dest = new JsonObject(); set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id); set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url, Converters.SESSION_URL); set(origin, VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title, null); set(origin, VendorAPISource.Topics.description, dest, OutputJsonKeys.Sessions.description, null); set(origin, VendorAPISource.Topics.start, dest, OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME); set(origin, VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp, Converters.DATETIME); JsonElement documents = get(origin, VendorAPISource.Topics.documents); if (documents != null && documents.isJsonArray() && documents.getAsJsonArray().size() > 0) { // Note that the input for SessionPhotoURL is the entity ID. We simply ignore the original // photo URL, because that will be processed by an offline cron script, resizing the // photos and saving them to a known location with the entity ID as its base name. set(origin, VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl, Converters.SESSION_PHOTO_URL); } setVideoPropertiesInSession(origin, dest); setRelatedVideos(origin, dest); JsonElement mainTag = null; JsonElement hashtag = null; JsonElement mainTagColor = null; JsonArray categories = origin.getAsJsonArray(VendorAPISource.Topics.categoryids.name()); JsonArray tags = new JsonArray(); for (JsonElement category : categories) { JsonObject tag = categoryToTagMap.get(category.getAsString()); if (tag != null) { JsonElement tagName = get(tag, OutputJsonKeys.Tags.tag); tags.add(tagName); usedTags.add(tagName.getAsString()); if (mainTag == null) { // check if the tag is from a "default" category. For example, if THEME is the default // category, all sessions will have a "mainTag" property set to the first tag of type THEME JsonElement tagCategory = get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC if (tagCategory.equals(mainCategory)) { mainTag = tagName; mainTagColor = get(tag, OutputJsonKeys.Tags.color); } if (hashtag == null && isHashtag(tag)) { hashtag = get(tag, OutputJsonKeys.Tags.hashtag); if (hashtag == null || hashtag.getAsString() == null || hashtag.getAsString().isEmpty()) { // If no hashtag set in the tagsconf file, we will convert the tagname to find one: hashtag = new JsonPrimitive( get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME).getAsString() .toLowerCase()); } } } } } set(tags, dest, OutputJsonKeys.Sessions.tags); if (mainTag != null) { set(mainTag, dest, OutputJsonKeys.Sessions.mainTag); } if (mainTagColor != null) { set(mainTagColor, dest, OutputJsonKeys.Sessions.color); } if (hashtag != null) { set(hashtag, dest, OutputJsonKeys.Sessions.hashtag); } JsonArray speakers = getAsArray(origin, VendorAPISource.Topics.speakerids); if (speakers != null) for (JsonElement speaker : speakers) { String speakerId = speaker.getAsString(); usedSpeakers.add(speakerId); } set(speakers, dest, OutputJsonKeys.Sessions.speakers); JsonArray sessions = origin.getAsJsonArray(VendorAPISource.Topics.sessions.name()); if (sessions != null && sessions.size() > 0) { String roomId = get(sessions.get(0).getAsJsonObject(), VendorAPISource.Sessions.roomid) .getAsString(); roomId = Config.ROOM_MAPPING.getRoomId(roomId); set(new JsonPrimitive(roomId), dest, OutputJsonKeys.Sessions.room); // captions URL is set based on the session room, so keep it here. String captionsURL = Config.ROOM_MAPPING.getCaptions(roomId); if (captionsURL != null) { set(new JsonPrimitive(captionsURL), dest, OutputJsonKeys.Sessions.captionsUrl); } } result.add(dest); } } return result; }
From source file:com.google.iosched.model.DataModelHelper.java
License:Open Source License
public static JsonPrimitive getMapValue(JsonElement map, String key, Converter converter, String defaultValueStr) { JsonPrimitive defaultValue = null;/*from w ww . ja v a 2 s .c om*/ if (defaultValueStr != null) { defaultValue = new JsonPrimitive(defaultValueStr); if (converter != null) defaultValue = converter.convert(defaultValue); } if (map == null || !map.isJsonArray()) { return defaultValue; } for (JsonElement el : map.getAsJsonArray()) { if (!el.isJsonObject()) { continue; } JsonObject obj = el.getAsJsonObject(); if (!obj.has("name") || !obj.has("value")) { continue; } if (key.equals(obj.getAsJsonPrimitive("name").getAsString())) { JsonElement value = obj.get("value"); if (!value.isJsonPrimitive()) { throw new ConverterException(value, converter, "Expected a JsonPrimitive"); } if (converter != null) value = converter.convert(value); return value.getAsJsonPrimitive(); } } return defaultValue; }