Example usage for org.json JSONArray get

List of usage examples for org.json JSONArray get

Introduction

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

Prototype

public Object get(int index) throws JSONException 

Source Link

Document

Get the object value associated with an index.

Usage

From source file:com.github.socialc0de.gsw.android.MainActivity.java

public static List<Object> toList(JSONArray array) throws JSONException {
    List<Object> list = new ArrayList<Object>();
    for (int i = 0; i < array.length(); i++) {
        Object value = array.get(i);
        if (value instanceof JSONArray) {
            value = toList((JSONArray) value);
        } else if (value instanceof JSONObject) {
            value = toMap((JSONObject) value);
        }/*from  ww w  . j  a  v  a 2  s  . com*/
        list.add(value);
    }
    return list;
}

From source file:com.github.sgelb.booket.SearchResultActivity.java

private void processResult(String result) {
    JSONArray items = null;
    try {/*w ww.  j  a v  a 2s .  c om*/
        JSONObject jsonObject = new JSONObject(result);
        items = jsonObject.getJSONArray("items");
    } catch (JSONException e) {
        noResults.setVisibility(View.VISIBLE);
        return;
    }

    try {

        // iterate over items aka books
        Log.d("R2R", "Items: " + items.length());
        for (int i = 0; i < items.length(); i++) {
            Log.d("R2R", "\nBook " + (i + 1));
            JSONObject item = (JSONObject) items.get(i);
            JSONObject info = item.getJSONObject("volumeInfo");
            Book book = new Book();

            // add authors
            String authors = "";
            if (info.has("authors")) {
                JSONArray jAuthors = info.getJSONArray("authors");
                for (int j = 0; j < jAuthors.length() - 1; j++) {
                    authors += jAuthors.getString(j) + ", ";
                }
                authors += jAuthors.getString(jAuthors.length() - 1);
            } else {
                authors = "n/a";
            }
            book.setAuthors(authors);
            Log.d("R2R", "authors " + book.getAuthors());

            // add title
            if (info.has("title")) {
                book.setTitle(info.getString("title"));
                Log.d("R2R", "title " + book.getTitle());
            }

            // add pageCount
            if (info.has("pageCount")) {
                book.setPageCount(info.getInt("pageCount"));
                Log.d("R2R", "pageCount " + book.getPageCount());
            }

            // add publisher
            if (info.has("publisher")) {
                book.setPublisher(info.getString("publisher"));
                Log.d("R2R", "publisher " + book.getPublisher());
            }

            // add description
            if (info.has("description")) {
                book.setDescription(info.getString("description"));
                Log.d("R2R", "description " + book.getDescription());
            }

            // add isbn
            if (info.has("industryIdentifiers")) {
                JSONArray ids = info.getJSONArray("industryIdentifiers");
                for (int k = 0; k < ids.length(); k++) {
                    JSONObject id = ids.getJSONObject(k);
                    if (id.getString("type").equalsIgnoreCase("ISBN_13")) {
                        book.setIsbn(id.getString("identifier"));
                        break;
                    }
                    if (id.getString("type").equalsIgnoreCase("ISBN_10")) {
                        book.setIsbn(id.getString("identifier"));
                    }
                }
                Log.d("R2R", "isbn " + book.getIsbn());
            }

            // add published date
            if (info.has("publishedDate")) {
                book.setYear(info.getString("publishedDate").substring(0, 4));
                Log.d("R2R", "publishedDate " + book.getYear());
            }

            // add cover thumbnail
            book.setThumbnailBitmap(defaultThumbnail);

            if (info.has("imageLinks")) {
                // get cover url from google
                JSONObject imageLinks = info.getJSONObject("imageLinks");
                if (imageLinks.has("thumbnail")) {
                    book.setThumbnailUrl(imageLinks.getString("thumbnail"));
                }
            } else if (book.getIsbn() != null) {
                // get cover url from amazon
                String amazonCoverUrl = "http://ecx.images-amazon.com/images/P/" + isbn13to10(book.getIsbn())
                        + ".01._SCMZZZZZZZ_.jpg";
                book.setThumbnailUrl(amazonCoverUrl);
            }

            // download cover thumbnail
            if (book.getThumbnailUrl() != null && !book.getThumbnailUrl().isEmpty()) {
                new DownloadThumbNail(book).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,
                        book.getThumbnailUrl());
                Log.d("R2R", "thumbnail " + book.getThumbnailUrl());
            }

            // add google book id
            if (item.has("id")) {
                book.setGoogleId(item.getString("id"));
            }

            bookList.add(book);

        }
    } catch (Exception e) {
        Log.d("R2R", "Exception: " + e.toString());
        // FIXME: catch exception
    }
}

From source file:com.example.android.swiperefreshlistfragment.SwipeRefreshListFragmentFragment.java

/**
 * Parsing json reponse and passing the data to feed view list adapter
 * *///from   ww w . j  a  va2s.  c o  m
private void parseJsonFeed(JSONObject response) {
    try {
        JSONArray feedArray = response.getJSONArray("feed");

        for (int i = 0; i < feedArray.length(); i++) {
            JSONObject feedObj = (JSONObject) feedArray.get(i);

            FeedItem item = new FeedItem();
            item.setId(feedObj.getInt("id"));
            item.setName(feedObj.getString("name"));

            // Image might be null sometimes
            String image = feedObj.isNull("image") ? null : feedObj.getString("image");
            item.setImge(image);
            item.setStatus(feedObj.getString("status"));
            item.setProfilePic(feedObj.getString("profilePic"));
            item.setTimeStamp(feedObj.getString("timeStamp"));

            // url might be null sometimes
            String feedUrl = feedObj.isNull("url") ? null : feedObj.getString("url");
            item.setUrl(feedUrl);

            mFeedItems.add(item);
        }

        // notify data changes to list adapater
        mFeedListAdapter.notifyDataSetChanged();
    } catch (JSONException e) {
        e.printStackTrace();
    }
}

From source file:com.trk.aboutme.facebook.SharedPreferencesTokenCachingStrategy.java

private void deserializeKey(String key, Bundle bundle) throws JSONException {
    String jsonString = cache.getString(key, "{}");
    JSONObject json = new JSONObject(jsonString);

    String valueType = json.getString(JSON_VALUE_TYPE);

    if (valueType.equals(TYPE_BOOLEAN)) {
        bundle.putBoolean(key, json.getBoolean(JSON_VALUE));
    } else if (valueType.equals(TYPE_BOOLEAN_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        boolean[] array = new boolean[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getBoolean(i);
        }/*from w w  w.  j a v a2s . co m*/
        bundle.putBooleanArray(key, array);
    } else if (valueType.equals(TYPE_BYTE)) {
        bundle.putByte(key, (byte) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_BYTE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        byte[] array = new byte[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (byte) jsonArray.getInt(i);
        }
        bundle.putByteArray(key, array);
    } else if (valueType.equals(TYPE_SHORT)) {
        bundle.putShort(key, (short) json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_SHORT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        short[] array = new short[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (short) jsonArray.getInt(i);
        }
        bundle.putShortArray(key, array);
    } else if (valueType.equals(TYPE_INTEGER)) {
        bundle.putInt(key, json.getInt(JSON_VALUE));
    } else if (valueType.equals(TYPE_INTEGER_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int[] array = new int[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getInt(i);
        }
        bundle.putIntArray(key, array);
    } else if (valueType.equals(TYPE_LONG)) {
        bundle.putLong(key, json.getLong(JSON_VALUE));
    } else if (valueType.equals(TYPE_LONG_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        long[] array = new long[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getLong(i);
        }
        bundle.putLongArray(key, array);
    } else if (valueType.equals(TYPE_FLOAT)) {
        bundle.putFloat(key, (float) json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_FLOAT_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        float[] array = new float[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = (float) jsonArray.getDouble(i);
        }
        bundle.putFloatArray(key, array);
    } else if (valueType.equals(TYPE_DOUBLE)) {
        bundle.putDouble(key, json.getDouble(JSON_VALUE));
    } else if (valueType.equals(TYPE_DOUBLE_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        double[] array = new double[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            array[i] = jsonArray.getDouble(i);
        }
        bundle.putDoubleArray(key, array);
    } else if (valueType.equals(TYPE_CHAR)) {
        String charString = json.getString(JSON_VALUE);
        if (charString != null && charString.length() == 1) {
            bundle.putChar(key, charString.charAt(0));
        }
    } else if (valueType.equals(TYPE_CHAR_ARRAY)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        char[] array = new char[jsonArray.length()];
        for (int i = 0; i < array.length; i++) {
            String charString = jsonArray.getString(i);
            if (charString != null && charString.length() == 1) {
                array[i] = charString.charAt(0);
            }
        }
        bundle.putCharArray(key, array);
    } else if (valueType.equals(TYPE_STRING)) {
        bundle.putString(key, json.getString(JSON_VALUE));
    } else if (valueType.equals(TYPE_STRING_LIST)) {
        JSONArray jsonArray = json.getJSONArray(JSON_VALUE);
        int numStrings = jsonArray.length();
        ArrayList<String> stringList = new ArrayList<String>(numStrings);
        for (int i = 0; i < numStrings; i++) {
            Object jsonStringValue = jsonArray.get(i);
            stringList.add(i, jsonStringValue == JSONObject.NULL ? null : (String) jsonStringValue);
        }
        bundle.putStringArrayList(key, stringList);
    } else if (valueType.equals(TYPE_ENUM)) {
        try {
            String enumType = json.getString(JSON_VALUE_ENUM_TYPE);
            @SuppressWarnings({ "unchecked", "rawtypes" })
            Class<? extends Enum> enumClass = (Class<? extends Enum>) Class.forName(enumType);
            @SuppressWarnings("unchecked")
            Enum<?> enumValue = Enum.valueOf(enumClass, json.getString(JSON_VALUE));
            bundle.putSerializable(key, enumValue);
        } catch (ClassNotFoundException e) {
        } catch (IllegalArgumentException e) {
        }
    }
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Object[][] getLatestTorrentsWithDetails(int set, int limit)
        throws JSONException, IOException, MalformedURLException, NoSuchAlgorithmException {
    Object[][] o = new Object[limit][2];
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;//from   w ww . java2s . co  m
    jSONObject = jsonReader.readJsonFromUrl(
            "http://ytsre.eu/api/list.json?set=" + Integer.toString(set) + "&limit=" + Integer.toString(limit));
    if (jSONObject.has("status")) {
        if (jSONObject.get("status").equals("fail")) {
            o = null;
        }
    } else {
        JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
        for (int i = 0; i < jSONArray.length(); i++) {
            JSONObject jsono = (JSONObject) jSONArray.get(i);
            int torrentID = Integer.parseInt(jsono.get("MovieID").toString());
            String imdbCode = jsono.get("ImdbCode").toString();
            o[i][0] = getTorrentDetails(torrentID);
            o[i][1] = imdbCode;
        }
    }
    return o;
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Object[][] getVideosAndTorrentsFromLatestTorrentsWithDetails(int set, int limit)
        throws ParseException, IOException, JSONException, MalformedURLException, NoSuchAlgorithmException {
    Object[][] o = new Object[limit][2];
    Collection<Torrent> torrentCollection = null;
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;/*from   w ww  . java  2  s. c  o m*/
    jSONObject = jsonReader.readJsonFromUrl(
            "http://ytsre.eu/api/list.json?set=" + Integer.toString(set) + "&limit=" + Integer.toString(limit));
    JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
    for (int i = 0; i < jSONArray.length(); i++) {
        JSONObject jsono = (JSONObject) jSONArray.get(i);
        IMDBGraber imdbg = new IMDBGraber();
        String imdbCode = jsono.get("ImdbCode").toString();
        torrentCollection = getAllTorrentsFromVideo(imdbCode);
        Video video = imdbg.getVideo(imdbCode);
        o[i][0] = video;
        o[i][1] = torrentCollection;
    }
    return o;
}

From source file:com.deltachi.videotex.grabers.YIFYGraber.java

private Collection<Torrent> getAllTorrentsFromVideo(String imdbCode)
        throws JSONException, IOException, MalformedURLException, NoSuchAlgorithmException {
    Collection<Torrent> torrentCollection = null;
    JSONReader jsonReader = new JSONReader();
    JSONObject jSONObject = null;/*from ww  w.  ja v  a 2s .c om*/
    jSONObject = jsonReader.readJsonFromUrl("http://ytsre.eu/api/listimdb.json?imdb_id=" + imdbCode);

    torrentCollection = new ArrayList<>();
    JSONArray jSONArray = (JSONArray) jSONObject.get("MovieList");
    for (int i = 0; i < jSONArray.length(); i++) {
        JSONObject json = (JSONObject) jSONArray.get(i);
        torrentCollection.add(getTorrentDetails(Integer.parseInt(json.get("MovieID").toString())));
    }
    return torrentCollection;
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse enroll(String jsonRequest, OxPush2Request oxPush2Request, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    if (request.has("registerRequests")) {
        JSONArray registerRequestArray = request.getJSONArray("registerRequests");
        if (registerRequestArray.length() == 0) {
            throw new U2FException("Failed to get registration request!");
        }// w w  w  .  j  a  v  a  2 s. c  om
        request = (JSONObject) registerRequestArray.get(0);
    }

    if (!request.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
        throw new U2FException("Unsupported U2F_V2 version!");
    }

    String version = request.getString(JSON_PROPERTY_VERSION);
    String appParam = request.getString(JSON_PROPERTY_APP_ID);
    String challenge = request.getString(JSON_PROPERTY_SERVER_CHALLENGE);
    String origin = oxPush2Request.getIssuer();

    EnrollmentResponse enrollmentResponse = u2fKey
            .register(new EnrollmentRequest(version, appParam, challenge, oxPush2Request));
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Enrollment response: " + enrollmentResponse);

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REGISTER_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_REGISTER);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, challenge);
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeRegisterResponse(enrollmentResponse);

    String deviceType = getDeviceType();
    String versionName = getVersionName();

    DeviceData deviceData = new DeviceData();
    deviceData.setUuid(DeviceUuidManager.getDeviceUuid(context).toString());
    deviceData.setPushToken(PushNotificationManager.getRegistrationId(context));
    deviceData.setType(deviceType);
    deviceData.setPlatform("android");
    deviceData.setName(Build.MODEL);
    deviceData.setOsName(versionName);
    deviceData.setOsVersion(Build.VERSION.RELEASE);

    String deviceDataString = new Gson().toJson(deviceData);

    JSONObject response = new JSONObject();
    response.put("registrationData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("deviceData", Utils.base64UrlEncode(deviceDataString.getBytes(Charset.forName("ASCII"))));

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(new String(challenge));
    tokenResponse.setKeyHandle(new String(enrollmentResponse.getKeyHandle()));

    return tokenResponse;
}

From source file:org.gluu.oxpush2.u2f.v2.SoftwareDevice.java

public TokenResponse sign(String jsonRequest, String origin, Boolean isDeny)
        throws JSONException, IOException, U2FException {
    if (BuildConfig.DEBUG)
        Log.d(TAG, "Starting to process sign request: " + jsonRequest);
    JSONObject request = (JSONObject) new JSONTokener(jsonRequest).nextValue();

    JSONArray authenticateRequestArray = null;
    if (request.has("authenticateRequests")) {
        authenticateRequestArray = request.getJSONArray("authenticateRequests");
        if (authenticateRequestArray.length() == 0) {
            throw new U2FException("Failed to get authentication request!");
        }//from  w  w w . j av a2s.  c o  m
    } else {
        authenticateRequestArray = new JSONArray();
        authenticateRequestArray.put(request);
    }

    Log.i(TAG, "Found " + authenticateRequestArray.length() + " authentication requests");

    AuthenticateResponse authenticateResponse = null;
    String authenticatedChallenge = null;
    JSONObject authRequest = null;
    for (int i = 0; i < authenticateRequestArray.length(); i++) {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Process authentication request: " + authRequest);
        authRequest = (JSONObject) authenticateRequestArray.get(i);

        if (!authRequest.getString(JSON_PROPERTY_VERSION).equals(SUPPORTED_U2F_VERSION)) {
            throw new U2FException("Unsupported U2F_V2 version!");
        }

        String version = authRequest.getString(JSON_PROPERTY_VERSION);
        String appParam = authRequest.getString(JSON_PROPERTY_APP_ID);
        String challenge = authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE);
        byte[] keyHandle = Base64.decode(authRequest.getString(JSON_PROPERTY_KEY_HANDLE),
                Base64.URL_SAFE | Base64.NO_WRAP);

        authenticateResponse = u2fKey.authenticate(new AuthenticateRequest(version,
                AuthenticateRequest.USER_PRESENCE_SIGN, challenge, appParam, keyHandle));
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Authentication response: " + authenticateResponse);
        if (authenticateResponse != null) {
            authenticatedChallenge = challenge;
            break;
        }
    }

    if (authenticateResponse == null) {
        return null;
    }

    JSONObject clientData = new JSONObject();
    if (isDeny) {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, AUTHENTICATE_CANCEL_TYPE);
    } else {
        clientData.put(JSON_PROPERTY_REQUEST_TYPE, REQUEST_TYPE_AUTHENTICATE);
    }
    clientData.put(JSON_PROPERTY_SERVER_CHALLENGE, authRequest.getString(JSON_PROPERTY_SERVER_CHALLENGE));
    clientData.put(JSON_PROPERTY_SERVER_ORIGIN, origin);

    String keyHandle = authRequest.getString(JSON_PROPERTY_KEY_HANDLE);
    String clientDataString = clientData.toString();
    byte[] resp = rawMessageCodec.encodeAuthenticateResponse(authenticateResponse);

    JSONObject response = new JSONObject();
    response.put("signatureData", Utils.base64UrlEncode(resp));
    response.put("clientData", Utils.base64UrlEncode(clientDataString.getBytes(Charset.forName("ASCII"))));
    response.put("keyHandle", keyHandle);

    TokenResponse tokenResponse = new TokenResponse();
    tokenResponse.setResponse(response.toString());
    tokenResponse.setChallenge(authenticatedChallenge);
    tokenResponse.setKeyHandle(keyHandle);

    return tokenResponse;
}

From source file:com.xgf.inspection.qrcode.google.zxing.client.result.supplement.BookResultInfoRetriever.java

@Override
void retrieveSupplementalInfo() throws IOException {

    CharSequence contents = HttpHelper.downloadViaHttp(
            "https://www.googleapis.com/books/v1/volumes?q=isbn:" + isbn, HttpHelper.ContentType.JSON);

    if (contents.length() == 0) {
        return;//w  w  w .  ja  v  a2  s.  c  o  m
    }

    String title;
    String pages;
    Collection<String> authors = null;

    try {

        JSONObject topLevel = (JSONObject) new JSONTokener(contents.toString()).nextValue();
        JSONArray items = topLevel.optJSONArray("items");
        if (items == null || items.isNull(0)) {
            return;
        }

        JSONObject volumeInfo = ((JSONObject) items.get(0)).getJSONObject("volumeInfo");
        if (volumeInfo == null) {
            return;
        }

        title = volumeInfo.optString("title");
        pages = volumeInfo.optString("pageCount");

        JSONArray authorsArray = volumeInfo.optJSONArray("authors");
        if (authorsArray != null && !authorsArray.isNull(0)) {
            authors = new ArrayList<String>(authorsArray.length());
            for (int i = 0; i < authorsArray.length(); i++) {
                authors.add(authorsArray.getString(i));
            }
        }

    } catch (JSONException e) {
        throw new IOException(e.toString());
    }

    Collection<String> newTexts = new ArrayList<String>();

    if (title != null && title.length() > 0) {
        newTexts.add(title);
    }

    if (authors != null && !authors.isEmpty()) {
        boolean first = true;
        StringBuilder authorsText = new StringBuilder();
        for (String author : authors) {
            if (first) {
                first = false;
            } else {
                authorsText.append(", ");
            }
            authorsText.append(author);
        }
        newTexts.add(authorsText.toString());
    }

    if (pages != null && pages.length() > 0) {
        newTexts.add(pages + "pp.");
    }

    String baseBookUri = "http://www.google." + LocaleManager.getBookSearchCountryTLD(context)
            + "/search?tbm=bks&source=zxing&q=";

    append(isbn, source, newTexts.toArray(new String[newTexts.size()]), baseBookUri + isbn);
}