Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

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

/*****************************************************************************
 * Creates a JSONObject object that contains the delete command for the 
 * specified playlist and adds it to the JSONArray that will pass the the 
 * command on to Google's servers. /*from  w ww. j  a v  a 2 s.  c om*/
 * 
 * @param context The context to use while deleting the playlist.
 * @param playlistId The playlistId of the playlist to delete.
 * @throws JSONException
 * @throws IllegalArgumentException
 *****************************************************************************/
public static final String deletePlaylist(Context context, String playlistId)
        throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    JSONArray mutationsArray = new JSONArray();

    mutationsArray.put(new JSONObject().put("delete", playlistId));
    jsonParam.put("mutations", mutationsArray);

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

    mHttpClient.setUserAgent(mWebClientUserAgent);
    return result;
}

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

/******************************************************************************************
 * Executes a single/batch modification operation on a playlist's entry(ies). This method 
 * is a general purpose method that simply hits the MobileClient endpoints using
 * mPlaylistEntriesMutationsArray. Supported mutation operations include "create", 
 * "delete", and "update". /*from  w w w .j a  v  a 2  s .co m*/
 * 
 * @param context The context to use while carrying out the modification operation.
 * @param mutationsArray The JSONArray that contains the mutations command to be 
 * carried out.
 * @return The JSON response as a String.
 * @throws JSONException
 * @throws IllegalArgumentException
 ******************************************************************************************/
public static final String modifyPlaylist(Context context) throws JSONException, IllegalArgumentException {

    JSONObject jsonParam = new JSONObject();
    jsonParam.put("mutations", mPlaylistEntriesMutationsArray);

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

    mHttpClient.setUserAgent(mWebClientUserAgent);

    //Clear out and reset the mutationsArray now that we're done using it.
    mPlaylistEntriesMutationsArray = null;
    mPlaylistEntriesMutationsArray = new JSONArray();

    return result;
}

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

/*******************************************************************************************
 * Sends a POST request to Google's servers and retrieves a JSONArray with all user 
 * playlists. The JSONArray contains the fields of the playlist such as "id", "name", 
 * "type", etc. (for a list of all response fields, see MobileClientPlaylistsSchema.java).
 * //from  w  ww.  j  a  v a 2 s. com
 * @return A JSONArray object that contains all user playlists and their fields.
 * @param context The context to use while retrieving user playlists.
 *******************************************************************************************/
public static final JSONArray getUserPlaylistsMobileClient(Context context)
        throws JSONException, IllegalArgumentException {

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

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

    mHttpClient.setUserAgent(mMobileClientUserAgent);
    String result = mHttpClient.post(context,
            "https://www.googleapis.com/sj/v1.1/playlistfeed?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) {
        playlistsJSONArray = dataJSONObject.getJSONArray("items");
    }

    return playlistsJSONArray;
}

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 www  .  j a v a  2 s. c o  m*/
 * @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   ww  w  . j  a v  a2  s.co  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:org.zaizi.sensefy.api.utils.JSONHelper.java

@SuppressWarnings("rawtypes")
public static Object toJSON(Object object) throws JSONException {
    if (object instanceof Map) {
        JSONObject json = new JSONObject();
        Map map = (Map) object;
        for (Object key : map.keySet()) {
            json.put(key.toString(), toJSON(map.get(key)));
        }//from   w ww  .  j  av  a2s.com
        return json;
    } else if (object instanceof Iterable) {
        JSONArray json = new JSONArray();
        for (Object value : ((Iterable) object)) {
            json.put(value);
        }
        return json;
    } else {
        return object;
    }
}

From source file:edu.stanford.mobisocial.dungbeetle.feed.objects.InviteToSharedAppFeedObj.java

public static JSONObject json(Collection<Contact> contacts, String feedName, String packageName) {
    JSONObject obj = new JSONObject();
    try {/*from   w w w.  j a v  a 2 s  .  c om*/
        obj.put("packageName", packageName);
        obj.put("sharedFeedName", feedName);
        JSONArray participants = new JSONArray();
        Iterator<Contact> it = contacts.iterator();
        while (it.hasNext()) {
            String localId = "@l" + it.next().id;
            participants.put(participants.length(), localId);
        }
        // Need to add ourself to participants
        participants.put(participants.length(), "@l" + Contact.MY_ID);
        obj.put("participants", participants);
    } catch (JSONException e) {
    }
    return obj;
}

From source file:io.riddles.lightriders.game.state.LightridersStateSerializer.java

private JSONObject visitState(LightridersState state) {
    JSONObject stateJson = new JSONObject();
    stateJson.put("round", state.getRoundNumber());

    JSONArray players = new JSONArray();
    for (LightridersPlayerState playerState : state.getPlayerStates()) {
        JSONObject playerObj = new JSONObject();
        playerObj.put("id", playerState.getPlayerId());
        playerObj.put("position", visitPoint(playerState.getCoordinate()));
        playerObj.put("isCrashed", !playerState.isAlive());

        if (playerState.getMove() != null && playerState.getMove().getException() != null) {
            playerObj.put("error", playerState.getMove().getException().getMessage());
        } else {/* w  ww . j  a v  a2  s .  c  om*/
            playerObj.put("error", JSONObject.NULL);
        }

        players.put(playerObj);
    }

    stateJson.put("players", players);
    return stateJson;
}

From source file:uk.bowdlerize.service.CensorCensusService.java

private void notifyOONIDirectly(String url, Pair<Boolean, Integer> results, String ISP, String SIM) {
    DefaultHttpClient httpclient = new DefaultHttpClient();
    JSONObject json;/*  w ww . jav a2s .  co  m*/
    HttpPost httpost = new HttpPost("https://blocked.org.uk/ooni-backend/submit");

    httpost.setHeader("Accept", "application/json");

    //I don't like YAML
    JSONObject ooniPayload = new JSONObject();

    //Lazy mass try / catch
    try {
        ooniPayload.put("agent", "Fake Agent");
        ooniPayload.put("body_length_match", false);
        ooniPayload.put("body_proportion", 1.0);
        ooniPayload.put("control_failure", null);
        ooniPayload.put("experiment_failure", null);
        ooniPayload.put("factor", 0.8);
        //ooniPayload.put("headers_diff",);
        ooniPayload.put("headers_match", false);

        //We only handle one request at the time but the spec specifies an array
        JSONObject ooniRequest = new JSONObject();
        ooniRequest.put("body", null);
        JSONObject requestHeaders = new JSONObject();
        for (Header hdr : headRequest.getAllHeaders()) {
            requestHeaders.put(hdr.getName(), hdr.getValue());
        }
        ooniRequest.put("headers", requestHeaders);
        ooniRequest.put("method", "HEAD");
        ooniRequest.put("url", url);

        JSONObject ooniResponse = new JSONObject();
        ooniResponse.put("body", "");
        ooniResponse.put("code", response.getStatusLine().getStatusCode());
        JSONObject responseHeaders = new JSONObject();
        for (Header hdr : response.getAllHeaders()) {
            responseHeaders.put(hdr.getName(), hdr.getValue());
        }

        ooniRequest.put("response", ooniResponse);

        JSONArray ooniRequests = new JSONArray();
        ooniRequests.put(ooniRequest);

        ooniPayload.put("requests", ooniRequests);

    } catch (Exception e) {
        e.printStackTrace();
    }

    try {
        httpost.setEntity(new StringEntity(ooniPayload.toString(), HTTP.UTF_8));

        HttpResponse response = httpclient.execute(httpost);
        String rawJSON = EntityUtils.toString(response.getEntity());
        response.getEntity().consumeContent();
        Log.e("ooni rawJSON", rawJSON);
        json = new JSONObject(rawJSON);

        //TODO In future versions we'll check for success and store it for later if it failed
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.imos.sample.pi.PythonTemperatureSensor.java

public void pythonTemperatureSensor() {

    try {/*from   w  w  w  .  j a va2 s.c  o  m*/
        String cmd = "sudo python /home/pi/Adafruit_Python_DHT/examples/AdafruitDHT.py 22 4";
        int count = 0;
        JSONArray array = new JSONArray();
        int dayOfMonth = 0;
        cal.setTime(new Date());
        dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
        while (true) {
            Process p = Runtime.getRuntime().exec(cmd);
            p.waitFor();

            StringBuilder output = new StringBuilder();
            BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String line = "";
            while ((line = reader.readLine()) != null) {
                output.append(line);
            }
            String result = output.toString(), tempStr;
            double temp, humid;
            if (result != null && !result.trim().isEmpty()) {
                tempStr = result.substring(result.indexOf("Humid"));
                result = result.substring(result.indexOf("=") + 1, result.indexOf("C") - 1);
                temp = Double.parseDouble(result);
                result = tempStr;
                result = result.substring(result.indexOf("=") + 1, result.indexOf("%"));
                humid = Double.parseDouble(result);

                JSONObject data = new JSONObject();
                data.put("temp", temp);
                data.put("humid", humid);
                data.put("time", new Date().getTime());

                array.put(data);
            }

            Thread.sleep(60000);
            count++;
            if (count == 60) {
                cal.setTime(new Date());
                StringBuilder builder = new StringBuilder();
                builder.append(cal.get(Calendar.DAY_OF_MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.MONTH));
                builder.append("-");
                builder.append(cal.get(Calendar.YEAR));
                builder.append("-");
                builder.append(cal.get(Calendar.HOUR_OF_DAY));
                builder.append("_");
                builder.append(cal.get(Calendar.MINUTE));
                String name = builder.toString();
                Logger.getLogger(PiMainFile.class.getName()).log(Level.INFO, "{0} recorded", name);
                try (BufferedWriter writer = new BufferedWriter(new FileWriter(name + "_data.json"))) {
                    writer.append(array.toString());
                } catch (IOException ex) {

                }
                System.out.println(builder.toString());
                count = 0;
                array = new JSONArray();
                if (dayOfMonth != cal.get(Calendar.DAY_OF_MONTH)) {
                    builder = new StringBuilder();
                    builder.append(cal.get(Calendar.DAY_OF_MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.MONTH));
                    builder.append("-");
                    builder.append(cal.get(Calendar.YEAR));
                    String dirName = builder.toString();
                    File newDir = new File("./" + dirName);
                    newDir.mkdir();

                    File files = new File("./");
                    for (File file : files.listFiles()) {
                        if (file.getName().endsWith(".json")) {
                            file.renameTo(new File("./" + dirName + File.separator + file.getName()));
                        }
                    }

                    dayOfMonth = cal.get(Calendar.DAY_OF_MONTH);
                }
            }
        }
    } catch (IOException | InterruptedException ex) {
        Logger.getLogger(PythonTemperatureSensor.class.getName()).log(Level.SEVERE, null, ex);
    }
}