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:org.vaadin.addons.locationtextfield.GoogleGeocoder.java

protected Collection<GeocodedLocation> createLocations(String address, String input) throws GeocodingException {
    final Set<GeocodedLocation> locations = new LinkedHashSet<GeocodedLocation>();
    try {//  w  w  w  .  j a v  a  2s  . c  o m
        JSONObject obj = new JSONObject(input);
        if ("OK".equals(obj.getString("status"))) {
            JSONArray results = obj.getJSONArray("results");
            boolean ambiguous = results.length() > 1;
            int limit = results.length();
            if (this.getLimit() > 0)
                limit = Math.min(this.getLimit(), limit);
            for (int i = 0; i < limit; i++) {
                JSONObject result = results.getJSONObject(i);
                GeocodedLocation loc = new GeocodedLocation();
                loc.setAmbiguous(ambiguous);
                loc.setOriginalAddress(address);
                loc.setGeocodedAddress(result.getString("formatted_address"));
                JSONArray components = result.getJSONArray("address_components");
                for (int j = 0; j < components.length(); j++) {
                    JSONObject component = components.getJSONObject(j);
                    String value = component.getString("short_name");
                    JSONArray types = component.getJSONArray("types");
                    for (int k = 0; k < types.length(); k++) {
                        String type = types.getString(k);
                        if ("street_number".equals(type))
                            loc.setStreetNumber(value);
                        else if ("route".equals(type))
                            loc.setRoute(value);
                        else if ("locality".equals(type))
                            loc.setLocality(value);
                        else if ("administrative_area_level_1".equals(type))
                            loc.setAdministrativeAreaLevel1(value);
                        else if ("administrative_area_level_2".equals(type))
                            loc.setAdministrativeAreaLevel2(value);
                        else if ("country".equals(type))
                            loc.setCountry(value);
                        else if ("postal_code".equals(type))
                            loc.setPostalCode(value);
                    }
                }
                JSONObject location = result.getJSONObject("geometry").getJSONObject("location");
                loc.setLat(location.getDouble("lat"));
                loc.setLon(location.getDouble("lng"));
                loc.setType(getLocationType(result));
                locations.add(loc);
            }
        }
    } catch (JSONException e) {
        throw new GeocodingException(e.getMessage(), e);
    }
    return locations;
}

From source file:org.vaadin.addons.locationtextfield.GoogleGeocoder.java

private LocationType getLocationType(JSONObject result) throws JSONException {
    if (!result.has("types"))
        return LocationType.UNKNOWN;
    JSONArray types = result.getJSONArray("types");
    for (int i = 0; i < types.length(); i++) {
        final String type = types.getString(i);
        if ("street_address".equals(type))
            return LocationType.STREET_ADDRESS;
        else if ("route".equals(type))
            return LocationType.ROUTE;
        else if ("intersection".equals(type))
            return LocationType.INTERSECTION;
        else if ("country".equals(type))
            return LocationType.COUNTRY;
        else if ("administrative_area_level_1".equals(type))
            return LocationType.ADMIN_LEVEL_1;
        else if ("administrative_area_level_2".equals(type))
            return LocationType.ADMIN_LEVEL_2;
        else if ("locality".equals(type))
            return LocationType.LOCALITY;
        else if ("neighborhood".equals(type))
            return LocationType.NEIGHBORHOOD;
        else if ("postal_code".equals(type))
            return LocationType.POSTAL_CODE;
        else if ("point_of_interest".equals(type))
            return LocationType.POI;
    }//from  w  w w  . ja  v  a2  s  . co m
    return LocationType.UNKNOWN;
}

From source file:info.aamulumi.tomate.APIConnection.java

/**
 * Send a GET request and create a list with returned JSON datas.
 * The JSONObject returned by server must have :
 * - success : int - 1 if request is successful
 * - data : JSONArray - contains datas which will be parsed
 *
 * @param url            - url to access
 * @param parseMethod    - name of the method used to parse an object in data
 * @param urlParameters  - parameters send in URL
 * @param bodyParameters - parameters send in body (encoded)
 * @return the list of parsed elements//from   w w  w  . j a v a  2s. c o m
 */
private static <T> ArrayList<T> getItems(String url, String parseMethod, HashMap<String, String> urlParameters,
        HashMap<String, String> bodyParameters) {
    ArrayList<T> list = new ArrayList<>();

    // Get parseMethod
    Class<?>[] cArg = new Class[1];
    cArg[0] = JSONObject.class;

    Method parse;
    try {
        parse = APIConnection.class.getMethod(parseMethod, cArg);
    } catch (NoSuchMethodException e1) {
        e1.printStackTrace();
        return null;
    }

    // Do the request
    JSONObject json = makeHttpRequest(url, GET, urlParameters, bodyParameters);

    if (json == null)
        return null;
    try {
        int success = json.getInt("success");
        // Parse if successful
        if (success == 1) {
            JSONArray data = json.getJSONArray("data");
            for (int i = 0; i < data.length(); i++) {
                @SuppressWarnings("unchecked")
                T tmp = (T) parse.invoke(APIConnection.class, data.getJSONObject(i));
                list.add(tmp);
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }

    return list;
}

From source file:com.chinaftw.music.model.MusicProvider.java

private synchronized void retrieveMedia() {
    try {/*from   w  w w  .  j  a v  a 2 s  . co  m*/
        if (mCurrentState == State.NON_INITIALIZED) {
            mCurrentState = State.INITIALIZING;

            JSONObject jsonObj = MusicAPI.getPlaylistDetails("60198");
            if (jsonObj == null) {
                return;
            }
            JSONArray tracks = jsonObj.getJSONArray(JSON_TRACKS);
            if (tracks != null) {
                for (int j = 0; j < 20; j++) {
                    MediaMetadata item = buildFromJSON(tracks.getJSONObject(j));
                    String musicId = item.getString(MediaMetadata.METADATA_KEY_MEDIA_ID);
                    mMusicListById.put(musicId, new MutableMediaMetadata(musicId, item));
                }
                buildListsByGenre();
            }
            mCurrentState = State.INITIALIZED;
        }
    } catch (JSONException e) {
        e.printStackTrace();
    } finally {
        if (mCurrentState != State.INITIALIZED) {
            // Something bad happened, so we reset state to NON_INITIALIZED to allow
            // retries (eg if the network connection is temporary unavailable)
            mCurrentState = State.NON_INITIALIZED;
        }
    }
}

From source file:com.chinaftw.music.model.MusicProvider.java

private MediaMetadata buildFromJSON(JSONObject json) throws JSONException {
    String id = String.valueOf(json.getInt(JSON_SONG_ID));
    String title = json.getString(JSON_TITLE);
    String album = json.getJSONObject(JSON_ALBUM).getString(JSON_ALBUM_NAME);
    String albumId = json.getJSONObject(JSON_ALBUM).getString(JSON_ALBUM_ID);
    String artist = json.getJSONArray(JSON_ARTIST).getJSONObject(0).getString(JSON_ARTIST_NAME);
    String artistId = json.getJSONObject(JSON_ALBUM).getString(JSON_ARTIST_ID);
    String imageId = json.getJSONObject(JSON_ALBUM).getString(JSON_ALBUM_IMAGE_ID);
    int duration = json.getInt(JSON_DURATION); // ms

    LogHelper.d(TAG, "Found music track: ", json);

    String source = MusicAPI.getSongUrl(id);
    String imageUri = MusicAPI.getPictureUrl(imageId);

    // Since we don't have a unique ID in the server, we fake one using the hashcode of
    // the music source. In a real world app, this could come from the server.

    // Adding the music source to the MediaMetadata (and consequently using it in the
    // mediaSession.setMetadata) is not a good idea for a real world music app, because
    // the session metadata can be accessed by notification listeners. This is done in this
    // sample for convenience only.
    return new MediaMetadata.Builder().putString(MediaMetadata.METADATA_KEY_MEDIA_ID, id)
            .putString(CUSTOM_METADATA_TRACK_SOURCE, source).putString(MediaMetadata.METADATA_KEY_ALBUM, album)
            .putString(MediaMetadata.METADATA_KEY_ARTIST, artist)
            .putLong(MediaMetadata.METADATA_KEY_DURATION, duration)
            .putString(MediaMetadata.METADATA_KEY_GENRE, "BILLBOARD") //TODO
            .putString(MediaMetadata.METADATA_KEY_TITLE, title)
            .putString(MediaMetadata.METADATA_KEY_ART_URI, imageUri)
            .putString(MediaMetadata.METADATA_KEY_ALBUM_ART_URI, imageUri)
            .putString(MediaMetadata.METADATA_KEY_DISPLAY_ICON_URI, imageUri).build();
}

From source file:com.vsu.bruteremote.FileBrowser.java

private FileBrowserItem[] parse(String jString) throws Exception {
    List<FileBrowserItem> items = new ArrayList<FileBrowserItem>();

    JSONObject jObject = new JSONObject(jString);

    String dir = jObject.getString("dir");
    JSONArray subdirArray = jObject.getJSONArray("subdir");
    JSONArray fileArray = jObject.getJSONArray("file");

    for (int ix = 0; ix < subdirArray.length(); ix++) {
        JSONObject obj = subdirArray.getJSONObject(ix);

        String display = obj.getString("display");
        String name = obj.getString("name");
        String path = obj.getString("path");

        items.add(new FileBrowserItem(display, name, dir, path, true));
    }/*from w w w  .j  a va  2s  .  c o m*/

    for (int ix = 0; ix < fileArray.length(); ix++) {
        JSONObject obj = fileArray.getJSONObject(ix);

        String display = obj.getString("display");
        String name = obj.getString("name");
        String path = obj.getString("path");

        items.add(new FileBrowserItem(display, name, dir, path, false));
    }

    return items.toArray(new FileBrowserItem[0]);
}

From source file:hongik.android.project.best.StoreReviewActivity.java

public void drawTable() throws Exception {
    String query = "func=morereview" + "&license=" + license;
    DBConnector conn = new DBConnector(query);
    conn.start();//from w w  w  .  j ava2 s.co  m

    conn.join();
    JSONObject jsonResult = conn.getResult();
    boolean result = jsonResult.getBoolean("result");

    if (!result) {
        return;
    }

    String storeName = jsonResult.getString("sname");
    ((TextViewPlus) findViewById(R.id.storereview_storename)).setText(storeName);

    JSONArray review = null;
    if (!jsonResult.isNull("review")) {
        review = jsonResult.getJSONArray("review");
    }

    //Draw Review Table
    if (review != null) {
        TableRow motive = (TableRow) reviewTable.getChildAt(1);

        for (int i = 0; i < review.length(); i++) {
            JSONObject json = review.getJSONObject(i);
            final String[] elements = new String[4];
            elements[0] = Double.parseDouble(json.getString("GRADE")) + "";
            elements[1] = json.getString("NOTE");
            elements[2] = json.getString("CID#");
            elements[3] = json.getString("DAY");

            TableRow tbRow = new TableRow(this);
            TextViewPlus[] tbCols = new TextViewPlus[4];

            if (elements[1].length() > 14)
                elements[1] = elements[1].substring(0, 14) + "...";

            for (int j = 0; j < 4; j++) {
                tbCols[j] = new TextViewPlus(this);
                tbCols[j].setText(elements[j]);
                tbCols[j].setLayoutParams(motive.getChildAt(j).getLayoutParams());
                tbCols[j].setGravity(Gravity.CENTER);
                tbCols[j].setTypeface(Typeface.createFromAsset(tbCols[j].getContext().getAssets(),
                        "InterparkGothicBold.ttf"));
                tbCols[j].setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent reviewIntent = new Intent(originActivity, ReviewDetailActivity.class);
                        reviewIntent.putExtra("ACCESS", "STORE");
                        reviewIntent.putExtra("CID", elements[2]);
                        reviewIntent.putExtra("LICENSE", license);
                        Log.i("StoreReview", "StartActivity");
                        startActivity(reviewIntent);
                    }
                });

                Log.i("StoreMenu", "COL" + j + ":" + elements[j]);
                tbRow.addView(tbCols[j]);
            }
            reviewTable.addView(tbRow);
        }
    }
    reviewTable.removeViewAt(1);
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private List<String> getPoshFingerprintsFromServer(String domain, String url, int maxTtl, boolean followUrl) {
    Log.d("mtm", "downloading json for " + domain + " from " + url);
    try {/*from  w  w w.ja v  a2 s  .  co m*/
        List<String> results = new ArrayList<>();
        HttpsURLConnection connection = (HttpsURLConnection) new URL(url).openConnection();
        connection.setConnectTimeout(5000);
        connection.setReadTimeout(5000);
        BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String inputLine;
        StringBuilder builder = new StringBuilder();
        while ((inputLine = in.readLine()) != null) {
            builder.append(inputLine);
        }
        JSONObject jsonObject = new JSONObject(builder.toString());
        in.close();
        int expires = jsonObject.getInt("expires");
        if (expires <= 0) {
            return new ArrayList<>();
        }
        if (maxTtl >= 0) {
            expires = Math.min(maxTtl, expires);
        }
        String redirect;
        try {
            redirect = jsonObject.getString("url");
        } catch (JSONException e) {
            redirect = null;
        }
        if (followUrl && redirect != null && redirect.toLowerCase().startsWith("https")) {
            return getPoshFingerprintsFromServer(domain, redirect, expires, false);
        }
        JSONArray fingerprints = jsonObject.getJSONArray("fingerprints");
        for (int i = 0; i < fingerprints.length(); i++) {
            JSONObject fingerprint = fingerprints.getJSONObject(i);
            String sha256 = fingerprint.getString("sha-256");
            if (sha256 != null) {
                results.add(sha256);
            }
        }
        writeFingerprintsToCache(domain, results, 1000L * expires + System.currentTimeMillis());
        return results;
    } catch (Exception e) {
        Log.d("mtm", "error fetching posh " + e.getMessage());
        return new ArrayList<>();
    }
}

From source file:de.duenndns.ssl.MemorizingTrustManager.java

private List<String> getPoshFingerprintsFromCache(String domain) {
    File file = getPoshCacheFile(domain);
    try {/* www. j av  a  2 s.c  om*/
        InputStream is = new FileInputStream(file);
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));

        String line = buf.readLine();
        StringBuilder sb = new StringBuilder();

        while (line != null) {
            sb.append(line).append("\n");
            line = buf.readLine();
        }
        JSONObject jsonObject = new JSONObject(sb.toString());
        is.close();
        long expires = jsonObject.getLong("expires");
        long expiresIn = expires - System.currentTimeMillis();
        if (expiresIn < 0) {
            file.delete();
            return null;
        } else {
            Log.d("mtm", "posh fingerprints expire in " + (expiresIn / 1000) + "s");
        }
        List<String> result = new ArrayList<>();
        JSONArray jsonArray = jsonObject.getJSONArray("fingerprints");
        for (int i = 0; i < jsonArray.length(); ++i) {
            result.add(jsonArray.getString(i));
        }
        return result;
    } catch (FileNotFoundException e) {
        return null;
    } catch (IOException e) {
        return null;
    } catch (JSONException e) {
        file.delete();
        return null;
    }
}

From source file:com.kevinquan.android.utils.JSONUtils.java

/**
 * Retrieve a JSON Array object stored at the provided key from the provided JSON object
 * @param obj The JSON object to retrieve from
 * @param key The key to retrieve/*from  www  .  ja  v a 2  s.c o  m*/
 * @return the JSON Array object stored in the key, or null if the key doesn't exist
 */
public static JSONArray safeGetArray(JSONObject obj, String key) {
    if (obj == null || TextUtils.isEmpty(key))
        return null;
    if (obj.has(key)) {
        try {
            return obj.getJSONArray(key);
        } catch (JSONException e) {
            Log.w(TAG, "Could not get JSONArray from key " + key, e);
        }
    }
    return null;
}