Example usage for org.json JSONObject getJSONArray

List of usage examples for org.json JSONObject getJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject getJSONArray.

Prototype

public JSONArray getJSONArray(String key) throws JSONException 

Source Link

Document

Get the JSONArray value associated with a key.

Usage

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/******************************************************************************************
 * Retrieves a JSONAray with all songs in <i><b>every</b></i> playlist. The JSONArray 
 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
 * of all fields, see MobileClientPlaylistEntriesSchema.java). 
 * //from  ww w .j  a va 2  s . c  om
 * @deprecated This method is fully functional. However, there are issues with retrieving 
 * the correct playlist entryIds. Specifically, the entryIds do not seem to work with 
 * reordering playlists via the MobileClient mutations protocol. 
 * 
 * @return A JSONArray object that contains all songs and their fields within every playlist. 
 * @param context The context to use while retrieving songs from the playlist.
 ******************************************************************************************/
public static final JSONArray getPlaylistEntriesMobileClient(Context context)
        throws JSONException, IllegalArgumentException {

    JSONArray playlistEntriesJSONArray = new JSONArray();
    JSONObject jsonRequestParams = new JSONObject();

    jsonRequestParams.put("max-results", 10000);
    jsonRequestParams.put("start-token", "0");

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/plentryfeed?alt=json&hl=en_US&tier=basic",
            new ByteArrayEntity(jsonRequestParams.toString().getBytes()), "application/json");

    JSONObject resultJSONObject = new JSONObject(result);
    JSONObject dataJSONObject = new JSONObject();

    if (resultJSONObject != null) {
        dataJSONObject = resultJSONObject.optJSONObject("data");
    }

    if (dataJSONObject != null) {
        playlistEntriesJSONArray = dataJSONObject.getJSONArray("items");
    }

    return playlistEntriesJSONArray;
}

From source file:com.aniruddhc.acemusic.player.GMusicHelpers.GMusicClientCalls.java

/**************************************************************************************************
 * Retrieves a JSONAray with all songs within the <b><i>specified</b></i> playlist. The JSONArray 
 * contains the fields of the songs such as "id", "clientId", "trackId", etc. (for a list 
 * of all fields, see WebClientSongsSchema.java). Uses the WebClient endpoint.
 * /*from  w  w w  . j a  v a2  s.  c o m*/
 * @return A JSONArray object that contains the songs and their fields within the specified playlist.
 * @param context The context to use while retrieving songs from the playlist.
 * @param playlistId The id of the playlist we need to fetch the songs from.
 **************************************************************************************************/
public static final JSONArray getPlaylistEntriesWebClient(Context context, String playlistId)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    jsonParam.putOpt("id", playlistId);

    JSONForm form = new JSONForm();
    form.addField("json", jsonParam.toString());
    form.close();

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://play.google.com/music/services/loadplaylist?u=0&xt=" + getXtCookieValue(),
            new ByteArrayEntity(form.toString().getBytes()), form.getContentType());

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject(result);

    if (jsonObject != null) {
        jsonArray = jsonObject.getJSONArray("playlist");
    }

    return jsonArray;
}

From source file:net.dv8tion.jda.core.handle.GuildEmojisUpdateHandler.java

@Override
protected Long handleInternally(JSONObject content) {
    final long guildId = content.getLong("guild_id");
    if (api.getGuildLock().isLocked(guildId))
        return guildId;

    GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId);
    if (guild == null) {
        api.getEventCache().cache(EventCache.Type.GUILD, guildId, () -> handle(responseNumber, allContent));
        return null;
    }/*from  w  w w  . j  a v  a  2 s .com*/

    JSONArray array = content.getJSONArray("emojis");
    TLongObjectMap<Emote> emoteMap = guild.getEmoteMap();
    List<Emote> oldEmotes = new ArrayList<>(emoteMap.valueCollection()); //snapshot of emote cache
    List<Emote> newEmotes = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
        JSONObject current = array.getJSONObject(i);
        final long emoteId = current.getLong("id");
        EmoteImpl emote = (EmoteImpl) emoteMap.get(emoteId);
        EmoteImpl oldEmote = null;

        if (emote == null) {
            emote = new EmoteImpl(emoteId, guild);
            newEmotes.add(emote);
        } else {
            // emote is in our cache which is why we don't want to remove it in cleanup later
            oldEmotes.remove(emote);
            oldEmote = emote.clone();
        }

        emote.setName(current.getString("name")).setManaged(current.getBoolean("managed"));
        //update roles
        JSONArray roles = current.getJSONArray("roles");
        Set<Role> newRoles = emote.getRoleSet();
        Set<Role> oldRoles = new HashSet<>(newRoles); //snapshot of cached roles
        for (int j = 0; j < roles.length(); j++) {
            Role role = guild.getRoleById(roles.getString(j));
            newRoles.add(role);
            oldRoles.remove(role);
        }

        //cleanup old cached roles that were not found in the JSONArray
        for (Role r : oldRoles) {
            // newRoles directly writes to the set contained in the emote
            newRoles.remove(r);
        }

        // finally, update the emote
        emoteMap.put(emote.getIdLong(), emote);
        // check for updated fields and fire events
        handleReplace(oldEmote, emote);
    }
    //cleanup old emotes that don't exist anymore
    for (Emote e : oldEmotes) {
        emoteMap.remove(e.getIdLong());
        api.getEventManager().handle(new EmoteRemovedEvent(api, responseNumber, e));
    }

    for (Emote e : newEmotes) {
        api.getEventManager().handle(new EmoteAddedEvent(api, responseNumber, e));
    }

    return null;
}

From source file:org.everit.json.schema.TestSuiteTest.java

@Parameters(name = "{2}")
public static List<Object[]> params() {
    List<Object[]> rval = new ArrayList<>();
    Reflections refs = new Reflections("org.everit.json.schema.draft4", new ResourcesScanner());
    Set<String> paths = refs.getResources(Pattern.compile(".*\\.json"));
    for (String path : paths) {
        if (path.indexOf("/optional/") > -1 || path.indexOf("/remotes/") > -1) {
            continue;
        }/*from w w w  .  j  a  va  2  s. c  o m*/
        String fileName = path.substring(path.lastIndexOf('/') + 1);
        JSONArray arr = loadTests(TestSuiteTest.class.getResourceAsStream("/" + path));
        for (int i = 0; i < arr.length(); ++i) {
            JSONObject schemaTest = arr.getJSONObject(i);
            JSONArray testcaseInputs = schemaTest.getJSONArray("tests");
            for (int j = 0; j < testcaseInputs.length(); ++j) {
                JSONObject input = testcaseInputs.getJSONObject(j);
                Object[] params = new Object[5];
                params[0] = "[" + fileName + "]/" + schemaTest.getString("description");
                params[1] = schemaTest.get("schema");
                params[2] = "[" + fileName + "]/" + input.getString("description");
                params[3] = input.get("data");
                params[4] = input.getBoolean("valid");
                rval.add(params);
            }
        }
    }
    return rval;
}

From source file:net.cellcloud.talk.HttpSpeaker.java

private void requestHeartbeat() {
    //  URL/*  w  w  w.  j  ava  2  s. c  o m*/
    StringBuilder url = new StringBuilder("http://");
    url.append(this.address.getHostString()).append(":").append(this.address.getPort());
    url.append(URI_HEARTBEAT);

    // ??
    try {
        ContentResponse response = this.client.newRequest(url.toString()).method(HttpMethod.GET)
                .header(HttpHeader.COOKIE, this.cookie).send();
        if (response.getStatus() == HttpResponse.SC_OK) {
            // 
            this.hbFailedCounts = 0;

            JSONObject responseData = this.readContent(response.getContent());
            if (responseData.has(HttpHeartbeatHandler.Primitives)) {
                // ?
                JSONArray primitives = responseData.getJSONArray(HttpHeartbeatHandler.Primitives);
                for (int i = 0, size = primitives.length(); i < size; ++i) {
                    JSONObject primJSON = primitives.getJSONObject(i);
                    // ??
                    this.doDialogue(primJSON);
                }
            }
        } else {
            // 
            ++this.hbFailedCounts;
            Logger.w(HttpSpeaker.class, "Heartbeat failed");
        }
    } catch (InterruptedException | TimeoutException | ExecutionException e) {
        // 
        ++this.hbFailedCounts;
    } catch (JSONException e) {
        Logger.log(getClass(), e, LogLevel.ERROR);
    }

    // hbMaxFailed ?
    if (this.hbFailedCounts >= this.hbMaxFailed) {
        this.hangUp();
    }
}

From source file:org.loklak.android.client.SearchClient.java

public static Timeline search(final String protocolhostportstub, final String query, final Timeline.Order order,
        final String source, final int count, final int timezoneOffset, final long timeout) throws IOException {
    Timeline tl = new Timeline(order);
    String urlstring = "";
    try {/*www  . ja v a  2 s .  c  o m*/
        urlstring = protocolhostportstub + "/api/search.json?q="
                + URLEncoder.encode(query.replace(' ', '+'), "UTF-8") + "&timezoneOffset=" + timezoneOffset
                + "&maximumRecords=" + count + "&source=" + (source == null ? "all" : source)
                + "&minified=true&timeout=" + timeout;
        JSONObject json = JsonIO.loadJson(urlstring);
        if (json == null || json.length() == 0)
            return tl;
        JSONArray statuses = json.getJSONArray("statuses");
        if (statuses != null) {
            for (int i = 0; i < statuses.length(); i++) {
                JSONObject tweet = statuses.getJSONObject(i);
                JSONObject user = tweet.getJSONObject("user");
                if (user == null)
                    continue;
                tweet.remove("user");
                UserEntry u = new UserEntry(user);
                MessageEntry t = new MessageEntry(tweet);
                tl.add(t, u);
            }
        }
        if (json.has("search_metadata")) {
            JSONObject metadata = json.getJSONObject("search_metadata");
            if (metadata.has("hits")) {
                tl.setHits((Integer) metadata.get("hits"));
            }
            if (metadata.has("scraperInfo")) {
                String scraperInfo = (String) metadata.get("scraperInfo");
                tl.setScraperInfo(scraperInfo);
            }
        }
    } catch (Throwable e) {
        Log.e("SeachClient", e.getMessage(), e);
    }
    //System.out.println(parser.text());
    return tl;
}

From source file:conroller.UserController.java

public static ArrayList<UserModel> userDetailsTable() throws IOException, JSONException {
    String userName, fullName, email, address, gender, telNo, password, typeOfUser;
    ArrayList<UserModel> arrayList = new ArrayList<>();
    phpConnection.setConnection(/* w  w w  .  j  a  v  a  2 s .c om*/
            "http://itmahaweliauthority.net23.net/MahaweliAuthority/userPHPfiles/UserGetView.php");
    JSONObject jSONObject = new JSONObject(phpConnection.readData());
    JSONArray array = jSONObject.getJSONArray("server_response");
    for (int i = 0; i < array.length(); i++) {
        JSONObject details = array.getJSONObject(i);
        try {
            userName = String.valueOf(details.getString("userName"));
        } catch (Exception e) {
            userName = null;
        }
        try {
            fullName = String.valueOf(details.getString("fullName"));
        } catch (Exception e) {
            fullName = null;
        }
        try {
            email = String.valueOf(details.getString("email"));
        } catch (Exception e) {
            email = null;
        }
        try {
            address = String.valueOf(details.getString("address"));
        } catch (Exception e) {
            address = null;
        }
        try {
            gender = String.valueOf(details.getString("gender"));
        } catch (Exception e) {
            gender = null;
        }
        try {
            telNo = String.valueOf(details.getString("telNo"));
        } catch (Exception e) {
            telNo = null;
        }
        try {
            password = String.valueOf(details.getString("password"));
        } catch (Exception e) {
            password = null;
        }
        try {
            typeOfUser = String.valueOf(details.getString("typeOfUser"));
        } catch (Exception e) {
            typeOfUser = null;
        }
        UserModel data = new UserModel(userName, fullName, email, address, gender, telNo, password, typeOfUser);
        arrayList.add(data);
    }
    return arrayList;
}

From source file:conroller.UserController.java

private static ArrayList<UserModel> getJSONData(String response) throws IOException, JSONException {
    String userName, fullName, email, address, gender, telNo, password, typeOfUser;
    ArrayList<UserModel> arrayList = new ArrayList<>();
    final JSONObject jSONObject = new JSONObject(response);
    final JSONArray array = jSONObject.getJSONArray("server_response");
    for (int i = 0; i < array.length(); i++) {
        final JSONObject details = array.getJSONObject(i);
        try {//w  w w. j a  v a2  s  .com
            userName = String.valueOf(details.getString("userName"));
        } catch (Exception ex) {
            userName = null;
        }
        try {
            fullName = String.valueOf(details.getString("fullName"));
        } catch (Exception e) {
            fullName = null;
        }
        try {
            email = String.valueOf(details.getString("email"));
        } catch (Exception e) {
            email = null;
        }
        try {
            address = String.valueOf(details.getString("address"));
        } catch (Exception e) {
            address = null;
        }
        try {
            gender = String.valueOf(details.getString("gender"));
        } catch (Exception e) {
            gender = null;
        }
        try {
            telNo = String.valueOf(details.getString("telNo"));
        } catch (Exception e) {
            telNo = null;
        }
        try {
            password = String.valueOf(details.getString("password"));
        } catch (Exception e) {
            password = null;
        }
        try {
            typeOfUser = String.valueOf(details.getString("typeOfUser"));
        } catch (Exception e) {
            typeOfUser = null;
        }
        UserModel model = new UserModel(userName, fullName, email, address, gender, telNo, password,
                typeOfUser);
        arrayList.add(model);
    }
    return arrayList;
}

From source file:rocks.teammolise.myunimol.webapp.login.HomeServlet.java

/**
  * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
  * methods./*ww  w.  j  a  v  a 2  s  .c  om*/
  *
  * @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 {
    //il tipo di risultato della servlet
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        if (request.getSession().getAttribute("userInfo") == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Unauthorized");
            return;
        }
        UserInfo userInfo = (UserInfo) request.getSession().getAttribute("userInfo");

        String username = userInfo.getUsername();
        String password = userInfo.getPassword();

        JSONObject recordBook = new APIConsumer().consume("getRecordBook", username, password);
        JSONObject result = new JSONObject();
        result.put("average", recordBook.getDouble("average"));
        result.put("weightedAverage", recordBook.getDouble("weightedAverage"));

        JSONArray exams = recordBook.getJSONArray("exams");
        float acquiredCFU = 0;
        int totalExams = 0;
        for (int i = 0; i < exams.length(); i++) {
            if (!exams.getJSONObject(i).getString("vote").contains("/")) {
                acquiredCFU += exams.getJSONObject(i).getInt("cfu");
                totalExams++;
            }
        }
        double percentCfuUgly = (acquiredCFU * 100) / userInfo.getTotalCFU();
        //Arrotonda la percentuale alla prima cifra decimale
        double percentCfu = Math.round(percentCfuUgly * 10D) / 10D;
        result.put("totalCFU", (int) userInfo.getTotalCFU());
        result.put("acquiredCFU", (int) acquiredCFU);
        result.put("percentCFU", percentCfu);
        result.put("totalExams", totalExams);

        out.write(result.toString());
    } catch (UnirestException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } catch (JSONException e) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Internal Server Error");
    } finally {
        out.close();
    }

}

From source file:org.wso2.carbon.dataservices.core.description.query.MongoQuery.java

private String getElementValueFromJson(String jsonString, JSONObject object, String jsonPath)
        throws JSONException {
    String value = null;/*from w w w . j ava 2 s . c  o m*/
    JSONObject tempObject = object;
    JSONArray tempArray;
    String[] tokens = jsonPath.split("\\.");
    if (tokens[0].equals(DBConstants.MongoDB.RESULT_COLUMN_NAME.toLowerCase())) {
        if (tokens.length == 1) {
            value = jsonString;
        } else {
            for (int i = 1; i < tokens.length; i++) {
                if (i == tokens.length - 1) {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        value = tempArray.getString((Integer) arrayObjects[1]);
                    } else {
                        value = tempObject.getString(tokens[i]);
                    }
                } else {
                    if (tokens[i].contains("[")) {
                        Object[] arrayObjects = getArrayElementKeys(tokens[i]);
                        tempArray = tempObject.getJSONArray(arrayObjects[0].toString());
                        tempObject = tempArray.getJSONObject((Integer) arrayObjects[1]);
                    } else {
                        tempObject = tempObject.getJSONObject(tokens[i]);
                    }
                }
            }
        }
        return value;
    } else {
        return null;
    }
}