List of usage examples for com.google.gson JsonObject getAsJsonArray
public JsonArray getAsJsonArray(String memberName)
From source file:com.yandex.money.api.typeadapters.model.showcase.uicontrol.SelectTypeAdapter.java
License:Open Source License
@Override protected void deserialize(JsonObject src, Select.Builder builder, JsonDeserializationContext context) { for (JsonElement item : src.getAsJsonArray(MEMBER_OPTIONS)) { JsonObject itemObject = item.getAsJsonObject(); JsonElement jsonGroup = itemObject.get(MEMBER_GROUP); Group group = null;//w w w. j a v a 2s . c om if (jsonGroup != null) { group = ListDelegate.deserialize(jsonGroup.getAsJsonArray(), context); } Select.Option option = new Select.Option(itemObject.get(MEMBER_LABEL).getAsString(), itemObject.get(MEMBER_VALUE).getAsString(), group); builder.addOption(option); } builder.setStyle(Select.Style.parse(getString(src, MEMBER_STYLE))); super.deserialize(src, builder, context); }
From source file:com.yandex.money.api.typeadapters.showcase.ShowcaseTypeAdapter.java
License:Open Source License
@Override public Showcase deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException { JsonObject object = json.getAsJsonObject(); return new Showcase.Builder().setTitle(getMandatoryString(object, MEMBER_TITLE)) .setHiddenFields(getNotNullMap(object, MEMBER_HIDDEN_FIELDS)) .setForm(ListDelegate.deserialize(object.getAsJsonArray(MEMBER_FORM), context)) .setMoneySources(new LinkedHashSet<>( getNotNullArray(object, MEMBER_MONEY_SOURCE, AllowedMoneySourceTypeAdapter.getInstance()))) .setErrors(getNotNullArray(object, MEMBER_ERROR, ErrorTypeAdapter.getInstance())).create(); }
From source file:com.yelinaung.hn.app.ui.MainActivity.java
License:Apache License
private void loadNews() { mSwipeView.setRefreshing(true);/*from w ww. j a v a 2 s . c o m*/ Ion.with(MainActivity.this).load("http://hnify.herokuapp.com/get/top").asString() .setCallback(new FutureCallback<String>() { @Override public void onCompleted(Exception e, String result) { try { if (e != null) throw e; mSwipeView.setRefreshing(false); JsonParser p = new JsonParser(); try { InputStream in = new ByteArrayInputStream(result.getBytes("UTF-8")); JsonReader reader = new JsonReader(new InputStreamReader(in, "UTF-8")); JsonObject storiesObject = (JsonObject) p.parse(reader); JsonArray storiesJsonArray = storiesObject.getAsJsonArray("stories"); Gson gson = new GsonBuilder().create(); stories.clear(); storyDao.deleteAllStories(); for (int i = 0; i < storiesJsonArray.size(); i++) { Story s = gson.fromJson((storiesJsonArray.get(i)).getAsJsonObject(), Story.class); stories.add(s); storyDao.create(s); } storyAdapter.notifyDataSetChanged(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } } catch (Exception ex) { ex.printStackTrace(); Toast.makeText(MainActivity.this, "Can't connect", Toast.LENGTH_SHORT).show(); mSwipeView.setRefreshing(false); } } }); }
From source file:com.zack6849.alphabot.api.PermissionManager.java
License:Open Source License
public void load() { Gson gson = new GsonBuilder().setPrettyPrinting().create(); try {//from w ww. jav a2 s . c om groups.clear(); String json = Files.toString(new File("permissions.json"), Charset.isSupported("UTF-8") ? Charset.forName("UTF-8") : Charset.defaultCharset()); JsonElement jelement = new JsonParser().parse(json); JsonObject output = jelement.getAsJsonObject(); JsonObject group = output.get("groups").getAsJsonObject(); Set<Map.Entry<String, JsonElement>> set = group.entrySet(); Iterator it = set.iterator(); while (it.hasNext()) { Map.Entry en = (Map.Entry) it.next(); JsonObject obj = new JsonParser().parse(en.getValue().toString()).getAsJsonObject(); String name = obj.get("name").toString().replaceAll("\"", ""); List<Permission> permissions = new ArrayList<Permission>(); //List<String> inheiritance = new ArrayList<String>(); boolean exec = obj.get("exec").getAsBoolean(); for (JsonElement perm : obj.getAsJsonArray("permissions")) { permissions.add(new Permission(perm.getAsString(), false)); } /*for(JsonElement inheirit : obj.getAsJsonArray("inheritance")){ inheiritance.add(inheirit.getAsString()); } */ groups.add(new Group(name, permissions, exec)); for (Group g : groups) { JsonObject gr = output.get("groups").getAsJsonObject().get(g.getName()).getAsJsonObject(); if (gr.has("inheritance")) { JsonArray inherit = gr.get("inheritance").getAsJsonArray(); List<String> inheritance = new ArrayList<String>(); for (int i = 0; i < inherit.size(); i++) { inheritance.add(inherit.get(i).getAsString()); } for (String in : inheritance) { Group ing = getGroupByName(in); g.addInherit(ing); } } } } } catch (Exception ex) { Logger.getLogger(PermissionManager.class.getName()).log(Level.SEVERE, null, ex); } }
From source file:com.zanvork.guildhub.model.Character.java
public Character(Map<String, String> characterData) { if (characterData.containsKey("name") && characterData.containsKey("realm") && characterData.containsKey("region")) { this.character_name = characterData.get("name"); String realmName = characterData.get("realm"); String region = characterData.get("region"); this.characterRealm = Realm.getRealm(realmName, region); String fields = ""; if (characterData.containsKey("fields")) { fields = characterData.get("fields"); }// w w w . jav a 2 s. c o m BattleNetDataRequest bnetRequest = new BattleNetDataRequest(); String bnetResponse = bnetRequest.loadCharacter(character_name, characterRealm, fields); JsonParser parser = new JsonParser(); JsonObject bnetJson = parser.parse(bnetResponse).getAsJsonObject(); this.character_name = bnetJson.get("name").getAsString(); this.realm_fk = characterRealm.getRealm_id(); this.race_fk = bnetJson.get("race").getAsInt(); this.characterRace = Race.getRace(race_fk); this.faction = characterRace.getFaction(); this.class_fk = bnetJson.get("class").getAsInt(); this.characterClass = Class.getClass(class_fk); //spec stuff this.spec_fk = -1; this.offspec_fk = -1; if (bnetJson.has("talents")) { JsonArray jsonTalents = bnetJson.getAsJsonArray("talents"); JsonObject jsonMainSpec = jsonTalents.get(0).getAsJsonObject(); String mainSpecName = ""; JsonObject jsonOffSpec = null; String offSpecName = ""; if (jsonTalents.size() > 1) { jsonOffSpec = jsonTalents.get(1).getAsJsonObject(); } if (jsonMainSpec.has("spec") && jsonMainSpec.getAsJsonObject("spec").has("name")) { mainSpecName = jsonMainSpec.getAsJsonObject("spec").get("name").getAsString(); this.characterMainSpec = Spec.getSpec(class_fk, mainSpecName); this.spec_fk = characterMainSpec.getSpec_id(); } if (jsonOffSpec != null && jsonOffSpec.has("spec") && jsonOffSpec.getAsJsonObject("spec").has("name")) { offSpecName = jsonOffSpec.getAsJsonObject("spec").get("name").getAsString(); this.characterOffSpec = Spec.getSpec(class_fk, offSpecName); this.offspec_fk = characterOffSpec.getSpec_id(); } } //TODO: set guild this.level = bnetJson.get("level").getAsInt(); this.thumbnail_url = bnetJson.get("thumbnail").getAsString(); this.user_fk = -1; } }
From source file:controllers.Rdio.java
License:Open Source License
public static Album retrieveAlbumByRdioId(User user, String album_key) { //Logger.info("Retrieving album by ID:" + album_key); Album album = Album.find("byRdio_Key", album_key).first(); if (album != null && album.tracksLoaded == true && album.albumTracks != null && album.albumTracks.size() > 1) { return album; }// w ww. j a v a2 s . c o m // Logger.info("Album not (fully) loaded, loading..."); WSRequest sign = null; String url = endpoint + "/albums/" + album_key + "?include=tracks,images"; boolean rerequest = false; try { sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET"); } catch (Exception ex) { Logger.error("User " + user.firstName + " had error with credentials"); Logger.error(ex.toString()); ex.printStackTrace(); rerequest = true; } if (rerequest) { setupTokens(user, null, 0); try { sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET"); } catch (Exception ex) { Logger.error(ex.toString()); ex.printStackTrace(); return null; } } JsonElement json = sign.get().getJson(); if (json.toString().equalsIgnoreCase("{\"code\":\"UnauthorizedError\",\"message\":\"Unauthorized\"}")) { json = reasssignCatalogAPIAccessToken(user, url, null); } if (json == null) { Logger.error("XZK:001 Null search result for " + user.firstName + " for album key" + album_key); return null; } JsonArray searchArray = json.getAsJsonObject().getAsJsonArray("albums"); JsonObject searchResult; if (searchArray == null) { Logger.error("Null searchArray in Rdio.java"); Logger.info(json.toString()); return null; } // Logger.info(searchArray.toString()); if (searchArray.size() < 1) { // @TODO Add flag to album to ignore in future Logger.error("Album " + album_key + " is missing from Napster catalog"); return null; } searchResult = searchArray.get(0).getAsJsonObject(); if (album == null) { Logger.info("No album at all, creating..0"); album = new Album(); } if (searchResult.get("name") == null) { Logger.error("Strange error:" + searchResult.toString()); return null; } album.rdio_key = album_key; album.name = searchResult.get("name").getAsString(); album.artist = searchResult.getAsJsonPrimitive("artistName").getAsString(); String dateString = searchResult.getAsJsonPrimitive("released").getAsString(); album.releaseDate = new DateTime(dateString).toDate(); JsonObject linked = searchResult.getAsJsonObject("linked"); JsonArray imagesArray = linked.getAsJsonArray("images"); JsonElement imageElement = imagesArray.get(0); album.icon = imageElement.getAsJsonObject().get("url").getAsString(); album.baseIcon = album.icon; album.bigIcon = album.icon; JsonArray tracks = linked.getAsJsonArray("tracks"); Iterator<JsonElement> iterator = tracks.iterator(); int trackNum = 1; album.albumTracks = new ArrayList<Track>(); int tracksAdded = 0; while (iterator.hasNext()) { JsonObject trackObj = iterator.next().getAsJsonObject(); Track track = Track.find("byRdio_Id", trackObj.get("id").getAsString()).first(); if (track == null) { track = new Track(); RdioHelper.parseNewTrack(user, track, trackObj, true); } // Make sure track is not already present boolean trackPresent = false; Iterator iter = album.albumTracks.iterator(); while (iter.hasNext()) { Track albumTrack = (Track) iter.next(); if (albumTrack.rdio_id == track.rdio_id) { trackPresent = true; break; } } if (trackPresent) { Logger.error("Trying to add a track to an album but it already exists in album!"); } else { tracksAdded++; track.album = album; album.albumTracks.add(track); } } album.tracksLoaded = true; album.save(); //Logger.info("Saved album " + album.rdio_key + " and added " + tracksAdded + " tracks."); return album; }
From source file:controllers.Rdio.java
License:Open Source License
public static List retrieveAlbumsForArtist(User user, String artist_key) { Logger.info("Rdio.retrieveAlbumsForArtist" + artist_key); // Now load discography ArrayList<Album> albumResults = new ArrayList(); WSRequest sign;//www .j a v a2 s. co m String url = endpoint + "artists/" + artist_key + "/albums" + "?apikey=" + Play.configuration.getProperty("rdio.key") + "&limit=200"; //Logger.info(url); try { sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET"); } catch (Exception ex) { Logger.error(ex.toString()); ex.printStackTrace(); return albumResults; } JsonElement searchResult = sign.get().getJson(); JsonElement albumsJsonElem = searchResult.getAsJsonObject().get("albums"); JsonArray albumsArray = albumsJsonElem.getAsJsonArray(); //Logger.info(searchResult.toString()); JsonArray discs = albumsArray; //Logger.info(discs.toString()); Iterator<JsonElement> iterator = discs.iterator(); while (iterator.hasNext()) { JsonElement elem = iterator.next(); JsonObject jsonAlbum = elem.getAsJsonObject(); String aKey = jsonAlbum.get("id").getAsString(); Album album = Album.find("byRdio_key", aKey).first(); if (album != null) { //Logger.info("Found album " + album.rdio_key); Album foundAlbum = album; AlbumRating albumRating = AlbumRating.find("byUserAndRdio_key", user, foundAlbum.rdio_key).first(); if (albumRating == null) { albumRating = new AlbumRating(); albumRating.rdio_key = foundAlbum.rdio_key; albumRating.user = user; albumRating.rating = -1L; albumRating.artist_name = foundAlbum.artist; albumRating.album_name = foundAlbum.name; albumRating.numOfRatingStars = LibraryItem.getStarCount(albumRating.rating); } foundAlbum.album_rating = albumRating; albumRating.save(); albumResults.add(foundAlbum); //Logger.info(foundAlbum.name); continue; } else { // Logger.info("No matches for album, so loading album " +artist_key); album = new Album(); album.albumTracks = new ArrayList(); } album.rdio_key = aKey; //Logger.info(jsonAlbum.toString()); album.name = jsonAlbum.get("name").getAsString(); album.artist = jsonAlbum.getAsJsonPrimitive("artistName").getAsString(); if (jsonAlbum.get("duration") != null) { album.duration = jsonAlbum.get("duration").getAsInt(); } // Grab album detail url = endpoint + "albums/" + album.rdio_key + "?include=tracks,images"; try { sign = getConnector(user).sign(user.rdioCreds, WS.url(url), "GET"); sign.setParameter("apikey", Play.configuration.getProperty("rdio.key")); sign.setParameter("limit", "100"); } catch (Exception ex) { Logger.error(ex.toString()); ex.printStackTrace(); return albumResults; } //Logger.info(url + "&apiKey="); elem = sign.get().getJson(); // Logger.info(elem.toString()); JsonArray albums = elem.getAsJsonObject().getAsJsonArray("albums"); JsonObject thisAlbum = albums.get(0).getAsJsonObject(); JsonObject linked = thisAlbum.get("linked").getAsJsonObject(); JsonArray images = linked.getAsJsonArray("images"); // Logger.info(thisAlbum.toString()); album.icon = images.get(0).getAsJsonObject().get("url").getAsString(); album.bigIcon = album.icon; album.baseIcon = album.icon; String dateString = thisAlbum.getAsJsonPrimitive("released").getAsString(); album.releaseDate = new DateTime(dateString).toDate(); album.duration = new Integer(0); JsonArray tracks = linked.getAsJsonArray("tracks").getAsJsonArray(); Iterator<JsonElement> trackIter = tracks.iterator(); while (trackIter.hasNext()) { JsonObject trackObj = trackIter.next().getAsJsonObject(); String trackId = trackObj.get("id").getAsString(); List AXtracks = Track.find("byRdio_id", trackId).fetch(); Track track = null; if (AXtracks.size() > 0) { track = (Track) AXtracks.get(0); } if (track == null) { track = new Track(); // track.rdio_id = trackObj.get("id").getAsString(); // the object key of the track // track.save(); RdioHelper.parseNewTrack(user, track, trackObj, true); track.coverArt = album.icon; } album.duration += (int) track.duration; } AlbumRating albumRating = AlbumRating.find("byUserAndRdio_key", user, album.rdio_key).first(); if (albumRating == null) { albumRating = new AlbumRating(); albumRating.rdio_key = album.rdio_key; albumRating.user = user; albumRating.rating = -1L; albumRating.artist_name = album.artist; albumRating.album_name = album.name; albumRating.numOfRatingStars = LibraryItem.getStarCount(albumRating.rating); } // Logger.info("Duration:" + album.duration); album = album.save(); album.album_rating = albumRating; albumRating.save(); albumResults.add(album); } return albumResults; }
From source file:csh.vctt.datautils.DataManager.java
License:Apache License
/** * Parses JSON into a Player Object.// ww w .j a va2 s. com * @param playerDatResults The JSON result of the player query to the API. * @return Player object. */ public static Player getPlayerFromAPIResults(String playerDatResults) { Player player = null; JsonElement root = new JsonParser().parse(playerDatResults); JsonObject outMemListObj = root.getAsJsonObject(); JsonArray outMemList = outMemListObj.getAsJsonArray(M_JSONMEM_CHARLIST); if (outMemList.size() != 0) { JsonElement playerDatE = outMemList.get(0); JsonObject playerDat = playerDatE.getAsJsonObject(); JsonObject nameObj = playerDat.getAsJsonObject(M_JSONMEM_CHAR_TOP_NAME); JsonObject brObj = playerDat.getAsJsonObject(M_JSONMEM_CHAR_TOP_BR); JsonObject certBalObj = playerDat.getAsJsonObject(M_JSONMEM_CHAR_TOP_CERTBAL); String id = getMemberAsStr(playerDat, M_JSONMEM_CHAR_ID); String name = getMemberAsStr(nameObj, M_JSONMEM_CHAR_NAME); String brStr = getMemberAsStr(brObj, M_JSONMEM_CHAR_BR); String certBalStr = getMemberAsStr(certBalObj, M_JSONMEM_CHAR_CERTBAL); int br = Integer.parseInt(brStr); int certBal = Integer.parseInt(certBalStr); if (id != null && !id.isEmpty()) { player = new Player(id, name, br, certBal); } else { System.err.println("PLAYER INIT ERROR: THERE WAS AN ERROR PARSING THE PLAYER DATA."); } } else { System.err.println("PLAYER INIT ERROR: THIS PLAYER DATA CORRUPTED OR INCORRECT."); } return player; }
From source file:csh.vctt.datautils.DataManager.java
License:Apache License
/** * Parses JSON into list containing the unique identifiers of certed items. * @param itemDat The JSON result of the item query to the API. * @return ArrayList<String> listing the items certed into. *//*from www . j a v a 2 s .c o m*/ public static ArrayList<String> getItemsFromAPIResults(String itemDat) { ArrayList<String> certs = new ArrayList<String>(); JsonElement root = new JsonParser().parse(itemDat); JsonObject rootObj = root.getAsJsonObject(); JsonArray certList = null; if (rootObj.has(M_JSONMEM_CERT_TOP_ITEM)) { certList = rootObj.getAsJsonArray(M_JSONMEM_CERT_TOP_ITEM); } else { System.err.println("CERT PARSE ERROR: INVALID JSON"); } if (certList != null) { for (JsonElement curCertElem : certList) { JsonObject curCertObj = curCertElem.getAsJsonObject(); certs.add(getMemberAsStr(curCertObj, M_JSONMEM_CERT_ITEM_ID)); } } return certs; }
From source file:csh.vctt.datautils.DataManager.java
License:Apache License
/** * Parses JSON into a SkillWrapper containing info about certed skills. * @param skillDat The JSON result of the skill query to the API. * @return SkillWrapper containing skill completion data. *///from ww w . j a va 2 s . c om public static SkillWrapper getSkillsFromAPIResults(String skillDat) { SkillWrapper skills = new SkillWrapper(); JsonElement root = new JsonParser().parse(skillDat); JsonObject rootObj = root.getAsJsonObject(); JsonArray certList = null; if (rootObj.has(M_JSONMEM_CERT_TOP_SKILL)) { certList = rootObj.getAsJsonArray(M_JSONMEM_CERT_TOP_SKILL); } else { System.err.println("CERT PARSE ERROR: INVALID JSON"); } if (certList != null) { for (JsonElement curCertElem : certList) { JsonObject curCertObj = curCertElem.getAsJsonObject(); JsonObject skillDatObj = curCertObj.getAsJsonObject(M_JSONMEM_CERT_TOP_SKILL_LINE); JsonObject nameObj = skillDatObj.getAsJsonObject(M_JSONMEM_CERT_TOP_SKILL_NAME); String id = getMemberAsStr(curCertObj, M_JSONMEM_CERT_SKILL_ID); String lineId = getMemberAsStr(skillDatObj, M_JSONMEM_CERT_SKILL_LINE_ID); String name = getMemberAsStr(nameObj, M_JSONMEM_CERT_SKILL_NAME); //Check if this skill is a line skill String lastChar = name.substring(name.length() - 1); boolean isInt = true; try { Integer.parseInt(lastChar); } catch (NumberFormatException e) { isInt = false; } if (isInt) { LineSkill lSkill = new LineSkill(id, lineId, name); lSkill.getId(); skills.addLineSkill(lSkill); } else { skills.addBasicSkill(id); } } } return skills; }