List of usage examples for com.google.gson JsonElement isJsonPrimitive
public boolean isJsonPrimitive()
From source file:com.nextdoor.bender.operation.json.key.KeyNameReplacementOperation.java
License:Apache License
protected void perform(JsonObject obj) { Set<Entry<String, JsonElement>> entries = obj.entrySet(); Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries); for (Entry<String, JsonElement> entry : orgEntries) { JsonElement val = entry.getValue(); /*// w w w . j a v a 2s .c om * See if key matches. If it does then drop or rename. Otherwise keep recursing. */ Matcher m = this.pattern.matcher(entry.getKey()); boolean found = m.find(); if (found) { /* * If instructed to drop then remove and continue. Otherwise remove and later rename; */ obj.remove(entry.getKey()); if (this.drop) { continue; } /* * Rename */ if (val.isJsonPrimitive()) { obj.add(m.replaceAll(this.replacement), val); } else if (val.isJsonObject()) { obj.add(m.replaceAll(this.replacement), val); perform(val.getAsJsonObject()); } else if (val.isJsonArray()) { JsonArray arr = val.getAsJsonArray(); arr.forEach(item -> { performOnArray(item); }); obj.add(m.replaceAll(this.replacement), val); } continue; } /* * Keep recursing */ if (val.isJsonObject()) { perform(val.getAsJsonObject()); } else if (val.isJsonArray()) { JsonArray arr = val.getAsJsonArray(); arr.forEach(item -> { performOnArray(item); }); } } }
From source file:com.nextdoor.bender.operation.json.key.LowerCaseKeyOperation.java
License:Apache License
protected void perform(JsonObject obj) { Set<Entry<String, JsonElement>> entries = obj.entrySet(); Set<Entry<String, JsonElement>> orgEntries = new HashSet<Entry<String, JsonElement>>(entries); for (Entry<String, JsonElement> entry : orgEntries) { JsonElement val = entry.getValue(); obj.remove(entry.getKey());/*from w ww .j ava2 s.c om*/ String key = entry.getKey().toLowerCase(); if (val.isJsonPrimitive()) { obj.add(key, val); } else if (val.isJsonObject()) { obj.add(key, val); perform(val.getAsJsonObject()); } else if (val.isJsonArray()) { obj.add(key, val); val.getAsJsonArray().forEach(elm -> { if (elm.isJsonObject()) { perform((JsonObject) elm); } }); } } }
From source file:com.nimbits.server.gson.EntityDeserializer.java
License:Apache License
@Override public Entity deserialize(final JsonElement jsonElement, final Type type, final JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { final String json; if (jsonElement.isJsonPrimitive()) { final JsonPrimitive jsonPrimitive = (JsonPrimitive) jsonElement; json = jsonPrimitive.getAsString(); } else {/*from ww w .java 2s . c om*/ json = jsonElement.toString(); } return new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create().fromJson(json, EntityModel.class); }
From source file:com.northernwall.hadrian.details.simple.SimpleHostDetailsHelper.java
License:Apache License
private void processAttribute(String prefix, Map.Entry<String, JsonElement> entry, List<GetPairData> pairs) { if (entry.getValue().isJsonPrimitive()) { addPair(prefix, entry.getKey(), entry.getValue().getAsString(), pairs); } else if (entry.getValue().isJsonArray()) { StringBuffer buffer = null; JsonArray jsonArray = entry.getValue().getAsJsonArray(); for (int i = 0; i < jsonArray.size(); i++) { JsonElement arrayElement = jsonArray.get(i); if (arrayElement.isJsonPrimitive()) { if (buffer == null) { buffer = new StringBuffer(arrayElement.getAsString()); } else { buffer.append(", "); buffer.append(arrayElement.getAsString()); }/*from w w w. j ava 2 s. c o m*/ } } if (buffer != null) { addPair(prefix, entry.getKey(), buffer.toString(), pairs); } } else if (entry.getValue().isJsonObject()) { JsonObject jsonObject = entry.getValue().getAsJsonObject(); for (Map.Entry<String, JsonElement> innerEntry : jsonObject.entrySet()) { processAttribute(entry.getKey(), innerEntry, pairs); } } }
From source file:com.openyelp.client.JsonRpcInvoker.java
License:Apache License
private Object work(String handleName, JsonRpcClientTransport transport, Method method, Object[] args, String key) {/* w w w .ja v a 2 s .co m*/ Gson gson = new Gson(); String cachekey = handleName + method.getName() + getKey(args); String keyy = Utils.getMD5Str(cachekey); String responseData = null; if (cache != null) { responseData = cache.get(keyy); if (responseData == null) { responseData = c(handleName, transport, method, args, key, gson); cache.put(keyy, responseData); } } else { responseData = c(handleName, transport, method, args, key, gson); } if (responseData == null) { if (diskCache != null) { responseData = diskCache.get(keyy); } } if (responseData == null) { return null; } JsonParser parser = new JsonParser(); JsonObject resp = (JsonObject) parser.parse(new StringReader(responseData)); // int sid = resp.get("id").getAsInt(); // if (id == sid) { // } else { // return null; // } JsonElement result = resp.get("result"); JsonElement error = resp.get("error"); /** * ?null */ if (error != null && !error.isJsonNull()) { if (error.isJsonPrimitive()) { System.out.println("<<>>>>>" + error.getAsString()); } else if (error.isJsonObject()) { JsonObject o = error.getAsJsonObject(); Integer code = (o.has("code") ? o.get("code").getAsInt() : null); String message = (o.has("message") ? o.get("message").getAsString() : null); String data = (o.has("data") ? (o.get("data") instanceof JsonObject ? o.get("data").toString() : o.get("data").getAsString()) : null); System.out.println(message + "<<>>>>>" + data); } else { System.out.println("<<>>>>>" + error.toString()); } return null; } if (diskCache != null) { System.out.println("?"); diskCache.put(keyy, responseData); } if (method.getReturnType() == void.class) { return null; } return gson.fromJson(result.toString(), method.getReturnType()); }
From source file:com.palechip.hudpixelmod.api.interaction.representations.Session.java
License:Open Source License
public ArrayList<String> getPlayers() { // make sure we don't convert the array twice if (this.playersArray == null) { this.playersArray = new ArrayList<String>(); for (JsonElement s : this.players) { if (s.isJsonPrimitive()) { this.playersArray.add(s.getAsString()); }//from w w w.j av a 2 s . c o m } } return this.playersArray; }
From source file:com.puppetlabs.geppetto.forge.v2.impl.AbstractForgeService.java
License:Open Source License
/** * Converts a java bean into a hash map using the beans json representation. * /*from w w w . ja va 2 s. c om*/ * @param bean * The bean to convert * @return The resulting map */ protected Map<String, String> toQueryMap(Object bean) { Map<String, String> result = new HashMap<String, String>(); if (bean != null) { JsonElement json = gson.toJsonTree(bean); if (json.isJsonObject()) { for (Map.Entry<String, JsonElement> entry : json.getAsJsonObject().entrySet()) { JsonElement element = entry.getValue(); if (element.isJsonPrimitive()) result.put(entry.getKey(), element.getAsString()); } } } return result; }
From source file:com.qmetry.qaf.automation.gson.GsonObjectDeserializer.java
License:Open Source License
public static Object read(JsonElement in) { if (in.isJsonArray()) { List<Object> list = new ArrayList<Object>(); JsonArray arr = in.getAsJsonArray(); for (JsonElement anArr : arr) { list.add(read(anArr));/*from www . j av a 2s .co m*/ } return list; } else if (in.isJsonObject()) { Map<String, Object> map = new LinkedTreeMap<String, Object>(); JsonObject obj = in.getAsJsonObject(); Set<Map.Entry<String, JsonElement>> entitySet = obj.entrySet(); for (Map.Entry<String, JsonElement> entry : entitySet) { map.put(entry.getKey(), read(entry.getValue())); } return map; } else if (in.isJsonPrimitive()) { JsonPrimitive prim = in.getAsJsonPrimitive(); if (prim.isBoolean()) { return prim.getAsBoolean(); } else if (prim.isString()) { return prim.getAsString(); } else if (prim.isNumber()) { if (prim.getAsString().contains(".")) return prim.getAsDouble(); else { return prim.getAsLong(); } } } return null; }
From source file:com.razza.apps.iosched.server.schedule.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 va2 s .c o m if (categoryToTagMap == null) { throw new IllegalStateException("You need to extract tags before attempting to extract sessions"); } JsonArray result = new JsonArray(); JsonDataSource source = sources.getSource(InputJsonKeys.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 = DataModelHelper.get(origin, InputJsonKeys.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(); // Some sessions require a special ID, so we replace it here... if (title != null && title.isJsonPrimitive() && "after hours".equalsIgnoreCase(title.getAsString())) { DataModelHelper.set(new JsonPrimitive("__afterhours__"), dest, OutputJsonKeys.Sessions.id); } else { DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.id); } DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.url, Converters.SESSION_URL); DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.title, dest, OutputJsonKeys.Sessions.title, obfuscate ? Converters.OBFUSCATE : null); DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.description, dest, OutputJsonKeys.Sessions.description, obfuscate ? Converters.OBFUSCATE : null); DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.start, dest, OutputJsonKeys.Sessions.startTimestamp, Converters.DATETIME); DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.finish, dest, OutputJsonKeys.Sessions.endTimestamp, Converters.DATETIME); DataModelHelper.set(new JsonPrimitive(isFeatured(origin)), dest, OutputJsonKeys.Sessions.isFeatured); JsonElement documents = DataModelHelper.get(origin, InputJsonKeys.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. DataModelHelper.set(origin, InputJsonKeys.VendorAPISource.Topics.id, dest, OutputJsonKeys.Sessions.photoUrl, Converters.SESSION_PHOTO_URL); } setVideoPropertiesInSession(origin, dest); setRelatedContent(origin, dest); JsonElement mainTag = null; JsonElement hashtag = null; JsonElement mainTagColor = null; JsonArray categories = origin .getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.categoryids.name()); JsonArray tags = new JsonArray(); for (JsonElement category : categories) { JsonObject tag = categoryToTagMap.get(category.getAsString()); if (tag != null) { JsonElement tagName = DataModelHelper.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 = DataModelHelper.get(tag, OutputJsonKeys.Tags.category); // THEME, TYPE or TOPIC if (tagCategory.equals(mainCategory)) { mainTag = tagName; mainTagColor = DataModelHelper.get(tag, OutputJsonKeys.Tags.color); } if (hashtag == null && DataModelHelper.isHashtag(tag)) { hashtag = DataModelHelper.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( DataModelHelper.get(tag, OutputJsonKeys.Tags.name, Converters.TAG_NAME) .getAsString().toLowerCase()); } } } } } DataModelHelper.set(tags, dest, OutputJsonKeys.Sessions.tags); if (mainTag != null) { DataModelHelper.set(mainTag, dest, OutputJsonKeys.Sessions.mainTag); } if (mainTagColor != null) { DataModelHelper.set(mainTagColor, dest, OutputJsonKeys.Sessions.color); } if (hashtag != null) { DataModelHelper.set(hashtag, dest, OutputJsonKeys.Sessions.hashtag); } JsonArray speakers = DataModelHelper.getAsArray(origin, InputJsonKeys.VendorAPISource.Topics.speakerids); if (speakers != null) for (JsonElement speaker : speakers) { String speakerId = speaker.getAsString(); usedSpeakers.add(speakerId); } DataModelHelper.set(speakers, dest, OutputJsonKeys.Sessions.speakers); JsonArray sessions = origin.getAsJsonArray(InputJsonKeys.VendorAPISource.Topics.sessions.name()); if (sessions != null && sessions.size() > 0) { String roomId = DataModelHelper .get(sessions.get(0).getAsJsonObject(), InputJsonKeys.VendorAPISource.Sessions.roomid) .getAsString(); roomId = Config.ROOM_MAPPING.getRoomId(roomId); DataModelHelper.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) { DataModelHelper.set(new JsonPrimitive(captionsURL), dest, OutputJsonKeys.Sessions.captionsUrl); } } if (Config.DEBUG_FIX_DATA) { DebugDataExtractorHelper.changeSession(dest, usedTags); } result.add(dest); } } return result; }
From source file:com.relayrides.pushy.apns.DateAsMillisecondsSinceEpochTypeAdapter.java
License:Open Source License
@Override public Date deserialize(final JsonElement json, final Type typeOfT, final JsonDeserializationContext context) throws JsonParseException { final Date date; if (json.isJsonPrimitive()) { date = new Date(json.getAsLong()); } else if (json.isJsonNull()) { date = null;/* w w w .j ava 2 s. c o m*/ } else { throw new JsonParseException( "Dates represented as seconds since the epoch must either be numbers or null."); } return date; }