Example usage for com.google.gson JsonObject getAsJsonObject

List of usage examples for com.google.gson JsonObject getAsJsonObject

Introduction

In this page you can find the example usage for com.google.gson JsonObject getAsJsonObject.

Prototype

public JsonObject getAsJsonObject(String memberName) 

Source Link

Document

Convenience method to get the specified member as a JsonObject.

Usage

From source file:com.yandex.money.api.typeadapters.RequestPaymentTypeAdapter.java

License:Open Source License

@Override
public RequestPayment deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject object = json.getAsJsonObject();

    RequestPayment.Builder builder = new RequestPayment.Builder()
            .setBalance(getBigDecimal(object, MEMBER_BALANCE))
            .setRecipientAccountStatus(AccountStatus.parse(getString(object, MEMBER_RECIPIENT_ACCOUNT_STATUS)))
            .setRecipientAccountType(AccountType.parse(getString(object, MEMBER_RECIPIENT_ACCOUNT_TYPE)))
            .setProtectionCode(getString(object, MEMBER_PROTECTION_CODE))
            .setAccountUnblockUri(getString(object, MEMBER_ACCOUNT_UNBLOCK_URI))
            .setExtActionUri(getString(object, MEMBER_EXT_ACTION_URI));

    JsonObject moneySourceObject = object.getAsJsonObject(MEMBER_MONEY_SOURCE);
    if (moneySourceObject != null) {
        builder.setMoneySources(MoneySourceListTypeAdapter.Delegate.deserialize(moneySourceObject, builder));
    }//  www  .  j a  v  a  2  s.c o m

    BaseRequestPaymentTypeAdapter.Delegate.deserialize(object, builder);
    return builder.create();
}

From source file:com.yandex.money.api.typeadapters.showcase.ShowcaseReferenceTypeAdapter.java

License:Open Source License

@Override
public ShowcaseReference deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
        throws JsonParseException {

    JsonObject object = json.getAsJsonObject();
    JsonObject paramsObject = object.getAsJsonObject(MEMBER_PARAMS);
    Map<String, String> params = paramsObject == null ? new HashMap<String, String>() : map(paramsObject);
    return new ShowcaseReference.Builder().setScid(getMandatoryLong(object, MEMBER_ID))
            .setTitle(getMandatoryString(object, MEMBER_TITLE)).setTopIndex(getInt(object, MEMBER_TOP))
            .setUrl(getString(object, MEMBER_URL))
            .setFormat(ShowcaseReference.Format.parse(getString(object, MEMBER_FORMAT))).setParams(params)
            .create();//  www.  j a  va 2 s .com
}

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");
        }/*from  w  w w  .j av  a  2s .  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  w  w  .j a va2 s . co  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:csh.vctt.datautils.DataManager.java

License:Apache License

/**
 * Parses JSON into a Player Object./*from  ww w.j  a va  2 s  . c om*/
 * @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 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   w w  w .  j av  a 2 s .com
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;
}

From source file:csh.vctt.datautils.DataManager.java

License:Apache License

/**
 * Parses JSON into Players.//from  w  ww.j a va 2 s  .  c o  m
 * @param outfitMembersJson The JSON result of the outfit member query to the API.
 * @return ArrayList containing Player objects for all outfit members.
 */
public static ArrayList<Player> getOutfitMembers(String outfitMembersJson) {
    ArrayList<Player> outfitMembers = new ArrayList<Player>();

    JsonElement root = new JsonParser().parse(outfitMembersJson);
    JsonObject obj = root.getAsJsonObject();
    JsonArray outfitMemArr = obj.getAsJsonArray(M_JSONMEM_OUTF_MEMLIST);

    for (JsonElement curCharE : outfitMemArr) {
        JsonObject curChar = curCharE.getAsJsonObject();

        if (curChar.has(M_JSONMEM_OUTF_TOP_CHAR)) {
            JsonObject charObj = curChar.getAsJsonObject(M_JSONMEM_OUTF_TOP_CHAR);

            JsonObject charNameObj = charObj.getAsJsonObject(M_JSONMEM_OUTF_TOP_CHAR_NAME);
            String id = getMemberAsStr(curChar, M_JSONMEM_OUTF_CHAR_ID);
            String name = getMemberAsStr(charNameObj, M_JSONMEM_OUTF_CHAR_NAME);

            outfitMembers.add(new Player(id, name));
        }
    }

    Collections.sort(outfitMembers);

    return outfitMembers;
}

From source file:cz.kovar.petr.homevoice.nlu.UserIntent.java

License:Open Source License

static UserIntent createFromJSON(JsonElement aRoot) {
    UserIntent result = new UserIntent();
    JsonObject rootobj = aRoot.getAsJsonObject();
    JsonObject entities = rootobj.getAsJsonObject("entities");
    Set<Map.Entry<String, JsonElement>> entries = entities.entrySet();
    for (Map.Entry<String, JsonElement> entry : entries) {
        result.m_entities.put(entry.getKey(), Entity.createFromJSON(entry));
        Log.e("WitHandler", Entity.createFromJSON(entry).toString());
    }//from   ww  w . j  ava2s  .c o  m
    return result;
}

From source file:cz.pchmelar.ddw.homework1.MainServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  ww w . jav  a2 s  . co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        /* TODO output your page here. You may use following sample code. */
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Simpsons Episode Analyzer</title>");
        out.println(
                "<link rel=\"stylesheet\" href=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css\">");
        out.println(
                "<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js\"></script>");
        out.println(
                "<script src=\"http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js\"></script>");
        out.println("</head>");
        out.println("<body style=\"background-color: #A0D1F5\">");

        out.println("<div class=\"container\">");
        out.println("<br>");
        out.println("<br>");
        out.println(
                "<a href=\"/ddw-homework1/MainServlet\"><img src=\"http://www.returndates.com/backgrounds/simpsons.logo.png\" class=\"img-responsive center-block\" style=\"width: 50%; height: 50%\"></a>");
        out.println("<br>");
        out.println("<br>");

        //GET JSON of all simpsons episodes
        String urlString = "http://api.tvmaze.com/singlesearch/shows?q=simpsons&embed=episodes";
        URL url = new URL(urlString);
        URLConnection conn = url.openConnection();
        InputStream is = conn.getInputStream();
        String JSON = IOUtils.toString(is, "UTF-8");

        //print season/episode/name for every episode in JSON
        JsonElement jelement = new JsonParser().parse(JSON);
        JsonObject jobject = jelement.getAsJsonObject();
        jobject = jobject.getAsJsonObject("_embedded");
        JsonArray jarray = jobject.getAsJsonArray("episodes");
        out.println("<table class=\"table table-bordered table-hover\" style=\"background-color: #FFFFFF\">");
        out.println("<thead><tr><th>Season</th><th>Episode</th><th>Name</th></tr></thead><tbody>");
        for (int i = 0; i < jarray.size(); i++) {

            jobject = jarray.get(i).getAsJsonObject();
            String season = jobject.get("season").toString();
            if (season.length() == 1)
                season = "0" + season;
            String episode = jobject.get("number").toString();
            if (episode.length() == 1)
                episode = "0" + episode;

            out.println("<tr>");
            out.println("<td>" + season + "</td>");
            out.println("<td>" + episode + "</td>");
            out.println("<td><a href=\"/ddw-homework1/DetailServlet?season=" + season + "&episode=" + episode
                    + "\">" + jobject.get("name").toString() + "</a></td>");
            out.println("</tr>");
        }
        out.println("</tbody></table>");
        out.println("</container>");

        out.println("</body>");
        out.println("</html>");
    }
}

From source file:dao.ChatDAO.java

public HashMap<Integer, Chat> getChatList(int staffId, String token)
        throws UnsupportedEncodingException, IOException, ParseException {
    HashMap<Integer, Chat> chatList = new HashMap<Integer, Chat>();
    //Add URL here
    String url = "http://119.81.43.85/chat/retrive_chat_list_history";

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url);

    // add header
    post.setHeader("User-Agent", USER_AGENT);

    //Add parameters here
    List<NameValuePair> urlParameters = new ArrayList<NameValuePair>();
    urlParameters.add(new BasicNameValuePair("staff_id", staffId + ""));
    urlParameters.add(new BasicNameValuePair("token", token));

    post.setEntity(new UrlEncodedFormEntity(urlParameters));

    HttpResponse response = client.execute(post);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

    StringBuffer result = new StringBuffer();
    String line = "";
    while ((line = rd.readLine()) != null) {
        result.append(line);//w ww .jav a2  s  . c  om
    }
    String str = result.toString();
    JsonParser jsonParser = new JsonParser();
    JsonElement element = jsonParser.parse(str);
    JsonObject jobj = element.getAsJsonObject();
    JsonObject jobj2 = jobj.getAsJsonObject("payload");
    JsonObject jobj3 = jobj2.getAsJsonObject("chat_history_list_result");
    JsonArray arr = jobj3.getAsJsonArray("generalList");
    int arrSize = arr.size();
    for (int i = 0; i < arrSize; i++) {
        //        for (int i = 0; i < arr.size(); i++) {
        JsonElement qrElement = arr.get(i);
        JsonObject qrObj = qrElement.getAsJsonObject();
        JsonElement attElement = qrObj.get("id");
        int id = 0;
        if (!attElement.isJsonNull()) {
            id = attElement.getAsInt();
        }
        attElement = qrObj.get("service_id");
        int service_id = 0;
        if (!attElement.isJsonNull()) {
            service_id = attElement.getAsInt();
        }
        attElement = qrObj.get("user_id");
        int user_id = 0;
        if (!attElement.isJsonNull()) {
            user_id = attElement.getAsInt();
        }
        attElement = qrObj.get("shop_id");
        int shop_id = 0;
        if (!attElement.isJsonNull()) {
            shop_id = attElement.getAsInt();
        }
        attElement = qrObj.get("last_message");
        String last_message = "";
        if (!attElement.isJsonNull()) {
            last_message = attElement.getAsString();
        }
        attElement = qrObj.get("modified");
        Timestamp modified = null;
        String dateTimeString = "1990-01-01 00:00:00";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        Date parsedDate = dateFormat.parse(dateTimeString);
        modified = new java.sql.Timestamp(parsedDate.getTime());
        if (attElement != null && !attElement.isJsonNull()) {
            dateTimeString = attElement.getAsString();
            dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            parsedDate = dateFormat.parse(dateTimeString);
            modified = new java.sql.Timestamp(parsedDate.getTime());
        }
        attElement = qrObj.get("created");
        Timestamp created = null;
        dateTimeString = "1990-01-01 00:00:00";
        dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        parsedDate = dateFormat.parse(dateTimeString);
        created = new java.sql.Timestamp(parsedDate.getTime());
        if (attElement != null && !attElement.isJsonNull()) {
            dateTimeString = attElement.getAsString();
            dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            parsedDate = dateFormat.parse(dateTimeString);
            created = new java.sql.Timestamp(parsedDate.getTime());
        }
        attElement = qrObj.get("deleted_at");
        Timestamp deleted_at = null;
        dateTimeString = "1990-01-01 00:00:00";
        dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        parsedDate = dateFormat.parse(dateTimeString);
        deleted_at = new java.sql.Timestamp(parsedDate.getTime());
        if (attElement != null && !attElement.isJsonNull()) {
            dateTimeString = attElement.getAsString();
            dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            parsedDate = dateFormat.parse(dateTimeString);
            deleted_at = new java.sql.Timestamp(parsedDate.getTime());
        }
        attElement = qrObj.get("user_name");
        String user_name = "";
        if (!attElement.isJsonNull()) {
            user_name = attElement.getAsString();
        }

        Chat chat = new Chat(id, service_id, user_id, shop_id, last_message, modified, created, deleted_at,
                user_name);
        chatList.put(i, chat);
    }
    return chatList;
}