List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.pmeade.arya.gson.deserialize.ParameterizedFieldDeserializer.java
License:Open Source License
/** * Request deserialization of a JSON array into a Collection<V> or * deserialization of a JSON object into a Map<K,V>. The deserialized * object will be populated in the provided field on the provided Object. * @param jo JsonObject containing the JSON to be deserialized * @param t Object to be populated with the parameterized content * @param field Field of the object to be populated (also identifies the * name of the JSON to be deserialized) * @throws IllegalAccessException never thrown (you don't actually believe * what I just told you, right?) *//*from ww w . jav a2 s . c o m*/ public void deserialize(JsonObject jo, Object t, Field field) throws IllegalAccessException { // if the provided JsonObject has JSON data mapped for the field if (jo.has(field.getName())) { // obtain the raw parameterized type (Collection, Map, etc.) ParameterizedType paraType = (ParameterizedType) field.getGenericType(); Class rawType = (Class) paraType.getRawType(); // if the raw type is assignable to Collection if (Collection.class.isAssignableFrom(rawType)) { // assume the JSON data is an array, and obtain in that format JsonArray ja = jo.getAsJsonArray(field.getName()); // deserialize the JSON array into a Collection object and // populate the field in the provided object field.set(t, deserializeCollection(ja, paraType)); } // otherwise, if the raw type is assignable to Map else if (Map.class.isAssignableFrom(rawType)) { // assume the JSON data is a JSON object, and obtain that JsonObject jo2 = jo.getAsJsonObject(field.getName()); // deserialize the JSON object into a Map object and // populate the field in the provided object field.set(t, deserializeMap(jo2, paraType)); } // otherwise, these aren't the droids we're looking for else { // we can go about our business ... move along throw new UnsupportedOperationException(); } } }
From source file:com.popdeem.sdk.core.deserializer.PDBrandsDeserializer.java
License:Open Source License
@Override public ArrayList<PDBrand> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("brands")) { Gson gson = new GsonBuilder().registerTypeAdapter(PDBrand.class, new PDBrandDeserializer()) .registerTypeAdapter(long.class, new PDLongDeserializer()) .registerTypeAdapter(int.class, new PDIntDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); JsonArray brandsArray = jsonObject.getAsJsonArray("brands"); return gson.fromJson(brandsArray, typeOfT); }// w w w .j av a2 s . c o m return new ArrayList<>(); }
From source file:com.popdeem.sdk.core.deserializer.PDFeedsDeserializer.java
License:Open Source License
@Override public ArrayList<PDFeed> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("feeds")) { Gson gson = new GsonBuilder().registerTypeAdapter(PDFeed.class, new PDFeedDeserializer()) .registerTypeAdapter(long.class, new PDLongDeserializer()) .registerTypeAdapter(int.class, new PDIntDeserializer()).create(); JsonArray feedsArray = jsonObject.getAsJsonArray("feeds"); return gson.fromJson(feedsArray, typeOfT); }/*from w ww .j a v a 2s. c o m*/ return new ArrayList<>(); }
From source file:com.popdeem.sdk.core.deserializer.PDMessagesDeserializer.java
License:Open Source License
@Override public ArrayList<PDMessage> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new GsonBuilder().registerTypeAdapter(long.class, new PDLongDeserializer()) .registerTypeAdapter(int.class, new PDIntDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("messages")) { JsonArray array = jsonObject.getAsJsonArray("messages"); return gson.fromJson(array, typeOfT); }/*from ww w . j a va 2s .c o m*/ return new ArrayList<>(); }
From source file:com.popdeem.sdk.core.deserializer.PDRewardsDeserializer.java
License:Open Source License
@Override public ArrayList<PDReward> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new GsonBuilder().registerTypeAdapter(PDReward.class, new PDRewardDeserializer()) .registerTypeAdapter(long.class, new PDLongDeserializer()) .registerTypeAdapter(int.class, new PDIntDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); JsonObject jsonObject = json.getAsJsonObject(); JsonArray array = jsonObject.getAsJsonArray("rewards"); return gson.fromJson(array, typeOfT); }
From source file:com.popdeem.sdk.core.deserializer.PDSocialMediaFriendsDeserializer.java
License:Open Source License
@Override public ArrayList<PDSocialMediaFriend> deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { Gson gson = new GsonBuilder() .registerTypeAdapter(PDSocialMediaFriend.class, new PDSocialMediaFriendDeserializer()) .setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create(); JsonObject jsonObject = json.getAsJsonObject(); if (jsonObject.has("data")) { JsonArray array = jsonObject.getAsJsonArray("data"); return gson.fromJson(array, typeOfT); }/*from w w w .j av a2 s. co m*/ return new ArrayList<>(); }
From source file:com.popdeem.sdk.uikit.fragment.PDUIWalletFragment.java
License:Open Source License
private void refreshWallet() { // deleteDirectoryTree(getActivity()); Log.i("PDUIWalletFragment", "Refreshing Wallet"); mSwipeRefreshLayout.post(new Runnable() { @Override// ww w .j a va 2 s . co m public void run() { mSwipeRefreshLayout.setRefreshing(true); } }); finishedWallet = false; finishedMessages = false; final PDRealmUserDetails userDetails = realm.where(PDRealmUserDetails.class).findFirst(); if (userDetails == null) { Log.i("PDUIWalletFragment", "refreshWallet: user is Null, clearing list"); mRewards.clear(); mAdapter.notifyDataSetChanged(); mSwipeRefreshLayout.setRefreshing(false); // mNoItemsInWalletView.setVisibility(mRewards.size() == 0 ? View.VISIBLE : View.GONE); mSwipeRefreshLayout.post(new Runnable() { @Override public void run() { Log.i("PDUIWalletFragment", "Removing refresh"); mSwipeRefreshLayout.setRefreshing(false); } }); } else { Log.i("PDUIWalletFragment", "refreshWallet: user exists"); // PDAPIClient.instance().getRewardsInWallet(new PDAPICallback<ArrayList<PDReward>>() { PDAPIClient.instance().getUserDetailsForId(userDetails.getId(), new PDAPICallback<JsonObject>() { @Override public void success(JsonObject jsonObject) { if (jsonObject.get("status").getAsString().equalsIgnoreCase("User Data")) { JsonObject user = jsonObject.getAsJsonObject("user"); float score = Float.valueOf(user.get("advocacy_score").getAsString()); realm.beginTransaction(); userDetails.setAdvocacyScore(score); realm.commitTransaction(); mAdapter.notifyDataSetChanged(); } } @Override public void failure(int statusCode, Exception e) { } }); PDAPIClient.instance().getRewardsInWallet(new PDAPICallback<JsonObject>() { @Override public void success(JsonObject jsonObject) { JsonArray jsonArray = jsonObject.getAsJsonArray("rewards"); ArrayList<PDReward> pdRewards = new ArrayList<PDReward>(); GsonBuilder gsonBuilder = new GsonBuilder(); gsonBuilder.registerTypeAdapter(PDReward.class, new PDRewardDeserializer()); Gson gson = gsonBuilder.create(); for (int i = 0; i < jsonArray.size(); i++) { PDReward reward = gson.fromJson(jsonArray.get(i), PDReward.class); pdRewards.add(reward); } // Sort rewards Collections.sort(pdRewards, new PDRewardComparator(PDRewardComparator.CLAIMED_AT_COMPARATOR)); // If a reward has been revoked, remove it from the users wallet int verifyingRewardIndex = -1; for (Iterator<PDReward> iterator = pdRewards.iterator(); iterator.hasNext();) { PDReward r = iterator.next(); if (r.getRevoked().equalsIgnoreCase("true")) { iterator.remove(); continue; } // if (mAutoVerifyRewardId != null && r.getId().equalsIgnoreCase(mAutoVerifyRewardId) && !r.isInstagramVerified()) { // r.setVerifying(true); // verifyingRewardIndex = pdRewards.indexOf(r); // mAutoVerifyRewardId = null; // } } JsonArray jsonArrayTiers = jsonObject.getAsJsonArray("tiers"); ArrayList<PDEvent> pdEvents = new ArrayList<PDEvent>(); Gson gsonEvents = new Gson(); for (int i = 0; i < jsonArrayTiers.size(); i++) { PDEvent event = gsonEvents.fromJson(jsonArrayTiers.get(i), PDEvent.class); pdEvents.add(event); } mRewards.clear(); mRewards.addAll(pdEvents); mRewards.addAll(pdRewards); Collections.sort(mRewards, new Comparator<Object>() { @Override public int compare(Object o1, Object o2) { long time1 = 0; long time2 = 0; if (o1 instanceof PDReward) { PDReward reward = (PDReward) o1; time1 = reward.getClaimedAt(); } else { PDEvent reward = (PDEvent) o1; time1 = reward.getDate(); } if (o2 instanceof PDReward) { PDReward reward = (PDReward) o2; time2 = reward.getClaimedAt(); } else { PDEvent reward = (PDEvent) o2; time2 = reward.getDate(); } if (time1 < time2) return 1; else if (time1 > time2) return -1; return 0; } }); mAdapter.notifyDataSetChanged(); finishedWallet = true; if (finishedMessages && finishedWallet) { mSwipeRefreshLayout.setRefreshing(false); } // mNoItemsInWalletView.setVisibility(mRewards.size() == 0 ? View.VISIBLE : View.GONE); // if (verifyingRewardIndex != -1) { // verifyReward(verifyingRewardIndex); // }else{ // PDUIGratitudeDialog.showGratitudeDialog(getActivity(), "share"); // } } @Override public void failure(int statusCode, Exception e) { finishedWallet = true; if (finishedMessages && finishedWallet) { mSwipeRefreshLayout.setRefreshing(false); } } }); } PDAPIClient.instance().getPopdeemMessages(new PDAPICallback<ArrayList<PDMessage>>() { @Override public void success(ArrayList<PDMessage> messages) { PDLog.d(PDUIInboxFragment.class, "message count: " + messages.size()); ArrayList<PDMessage> mMessages = new ArrayList<>(); mMessages.addAll(messages); int unread = 0; for (int i = 0; i < messages.size(); i++) { if (!messages.get(i).isRead()) { unread++; } } setBadges(unread); finishedMessages = true; if (finishedMessages && finishedWallet) { mSwipeRefreshLayout.setRefreshing(false); } } @Override public void failure(int statusCode, Exception e) { finishedMessages = true; if (finishedMessages && finishedWallet) { mSwipeRefreshLayout.setRefreshing(false); } } }); }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
License:Open Source License
public boolean loginKeystone() throws UnknownHostException, SocketException, IOException, UnauthorizeException { isLoggedin = false;//from w w w . j av a 2s .c o m String tenantNameKeystone = ""; String userNameKeystone = username; if (username.split(":").length >= 2) { tenantNameKeystone = username.split(":")[0]; userNameKeystone = username.split(":")[1]; } String content = "{\"auth\": {\"passwordCredentials\": {\"username\": \"" + userNameKeystone + "\", \"password\": \"" + password + "\"}, \"tenantName\":\"" + tenantNameKeystone + "\"}}"; HttpPost method = new HttpPost(authenticationURL); method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut); method.setHeader("Content-type", "application/json"); InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); InputStreamEntity entity = new InputStreamEntity(stream, content.getBytes("UTF-8").length); method.setEntity(entity); stream.close(); FilesResponse response = new FilesResponse(client.execute(method)); if (response.getStatusCode() == 401) { throw new UnauthorizeException("Incorrect user/password.", response.getResponseHeaders(), response.getStatusLine()); } InputStream in = response.getResponseBodyAsStream(); String outString = IOUtils.toString(in, "UTF-8"); in.close(); JsonElement jelement = new JsonParser().parse(outString); JsonObject jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("access"); jobject = jobject.getAsJsonObject("token"); authToken = jobject.get("id").getAsString(); jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("access"); JsonArray jarray = jobject.getAsJsonArray("serviceCatalog"); for (JsonElement serviceCatalog : jarray) { JsonObject jsonLineItem = serviceCatalog.getAsJsonObject(); String value = jsonLineItem.get("type").getAsString(); if (value.compareTo("object-store") == 0) { JsonArray jarray2 = jsonLineItem.getAsJsonArray("endpoints"); JsonElement endpoint = jarray2.get(0); storageURL = endpoint.getAsJsonObject().get("publicURL").getAsString(); isLoggedin = true; cdnManagementURL = ""; break; } } logger.debug("storageURL: " + storageURL); logger.debug("authToken: " + authToken); logger.debug("cdnManagementURL:" + cdnManagementURL); logger.debug("ConnectionManager:" + client.getConnectionManager()); return isLoggedin; }
From source file:com.rackspacecloud.client.cloudfiles.FilesClient.java
License:Open Source License
public boolean loginKeystoneV3() throws UnknownHostException, SocketException, IOException, UnauthorizeException { isLoggedin = false;/*ww w.j av a2 s.c om*/ String tenantNameKeystone = ""; String userNameKeystone = username; if (username.split(":").length >= 2) { tenantNameKeystone = username.split(":")[0]; userNameKeystone = username.split(":")[1]; } String content = "{\"auth\": {\"identity\": {\"methods\": [\"password\"],\"password\": {\"user\":{\"domain\": {\"name\": \"d_Stacksync\"},\"name\": \"" + userNameKeystone + "\",\"password\": \"" + password + "\"}}},\"scope\": {\"project\": {\"domain\": {\"name\": \"d_Stacksync\"},\"name\": \"" + tenantNameKeystone + "\"}}}}"; //String content = "{\"auth\": {\"passwordCredentials\": {\"username\": \"" + userNameKeystone + "\", \"password\": \"" + password + "\"}, \"tenantName\":\"" + tenantNameKeystone + "\"}}"; HttpPost method = new HttpPost(authenticationURL); method.getParams().setIntParameter("http.socket.timeout", connectionTimeOut); method.setHeader("Content-type", "application/json"); InputStream stream = new ByteArrayInputStream(content.getBytes("UTF-8")); InputStreamEntity entity = new InputStreamEntity(stream, content.getBytes("UTF-8").length); method.setEntity(entity); stream.close(); FilesResponse response = new FilesResponse(client.execute(method)); if (response.getStatusCode() == 401) { throw new UnauthorizeException("Incorrect user/password.", response.getResponseHeaders(), response.getStatusLine()); } InputStream in = response.getResponseBodyAsStream(); String outString = IOUtils.toString(in, "UTF-8"); in.close(); Header header = response.getResponseHeaders("X-Subject-Token")[0]; authToken = header.getValue(); JsonElement jelement = new JsonParser().parse(outString); JsonObject jobject = jelement.getAsJsonObject(); //jobject = jelement.getAsJsonObject(); jobject = jobject.getAsJsonObject("token"); JsonArray jarray = jobject.getAsJsonArray("catalog"); for (JsonElement serviceCatalog : jarray) { JsonObject jsonLineItem = serviceCatalog.getAsJsonObject(); String value = jsonLineItem.get("type").getAsString(); if (value.compareTo("object-store") == 0) { JsonArray jarray2 = jsonLineItem.getAsJsonArray("endpoints"); for (JsonElement endpoint : jarray2) { JsonObject endpointObject = endpoint.getAsJsonObject(); String publicURL = endpointObject.get("interface").getAsString(); if (publicURL.compareTo("public") == 0) { storageURL = endpointObject.get("url").getAsString(); isLoggedin = true; cdnManagementURL = ""; break; } } } } logger.debug("storageURL: " + storageURL); logger.debug("authToken: " + authToken); logger.debug("cdnManagementURL:" + cdnManagementURL); logger.debug("ConnectionManager:" + client.getConnectionManager()); return isLoggedin; }
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 av a2 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; }