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:org.protorabbit.json.JSONUtil.java

@SuppressWarnings("unchecked")
public static Object cloneJSON(Object target) {

    if (target == null)
        return JSONObject.NULL;

    if (target instanceof JSONObject) {
        Object o = null;// ww  w .  ja  va  2  s  .  c om
        o = new JSONObject();
        JSONObject jo = (JSONObject) target;
        Iterator<String> it = jo.keys();
        while (it.hasNext()) {
            String key = it.next();
            try {
                ((JSONObject) o).put(key, cloneJSON(jo.get(key)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        return o;
    } else if (target instanceof JSONArray) {
        Object o = new JSONArray();
        JSONArray ja = (JSONArray) target;
        int len = ja.length();
        for (int i = 0; i < len; i++) {
            try {
                ((JSONArray) o).put(cloneJSON(ja.get(i)));
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    } else if (target instanceof Long) {
        return new Long(((Long) target).longValue());
    } else if (target instanceof Double) {
        return new Double(((Double) target).doubleValue());
    } else if (target instanceof Integer) {
        return new Integer(((Integer) target).intValue());
    } else if (target instanceof Boolean) {
        return new Boolean(((Boolean) target).booleanValue());
    }
    return target;
}

From source file:org.protorabbit.json.JSONUtil.java

public static void concatJSONArrays(JSONArray parent, JSONArray child) throws JSONException {
    for (int i = 0; i < child.length(); i++) {
        parent.put(child.get(i));
    }//from   w w w  .j  a  va 2s.c om
}

From source file:$.ExampleResourceTest.java

@Test
    public void getPages() throws Exception {
        JSONObject json = resource.getPages();
        assertNotNull(json);/*w ww  .  ja v  a 2s.c  om*/
        assertTrue(json.has("pages"));
        JSONArray pages = json.getJSONArray("pages");
        assertNotNull(pages);
        assertEquals(sitePages.size(), pages.length());
        for (int i = 0; i < pages.length(); i++) {
            assertEquals("Page " + i, pages.get(i));
        }
    }

From source file:net.dahanne.gallery3.client.business.G3Client.java

private Item getItems(int albumId, List<Item> items, String type) throws G3GalleryException {
    logger.debug("getting items in albumId : {}, type : {}", albumId, type);
    Item item = this.getItem(albumId);
    Collection<String> members = item.getMembers();
    JSONArray urls = new JSONArray(members);
    try {/*from  w  w w.j ava2 s .  c  o m*/
        String encodedUrls;
        encodedUrls = URLEncoder.encode(urls.toString(), "UTF-8");
        StringBuilder requestToAppend = new StringBuilder();
        requestToAppend.append(INDEX_PHP_REST_ITEMS);
        requestToAppend.append("?urls=");
        requestToAppend.append(encodedUrls);
        requestToAppend.append("&type=");
        requestToAppend.append(type);
        String sendHttpRequest = sendHttpRequest(requestToAppend.toString(), new ArrayList<NameValuePair>(),
                GET, null);

        JSONTokener jsonTokener = new JSONTokener(sendHttpRequest);
        JSONArray jsonResult = (JSONArray) jsonTokener.nextValue();
        for (int i = 0; i < jsonResult.length(); i++) {
            items.add(ItemUtils.parseJSONToItem((JSONObject) jsonResult.get(i)));
        }
    } catch (UnsupportedEncodingException e) {
        throw new G3GalleryException(e);
    } catch (JSONException e) {
        throw new G3GalleryException(e);
    }
    return item;
}

From source file:com.vk.sdk.util.VKJsonHelper.java

/**
* Converts json-array to list/*from www .  ja va 2 s  .c  o  m*/
* @param array json-array to convert
* @return converted array
* @throws JSONException
*/
@SuppressWarnings("unchecked")
public static List toList(JSONArray array) throws JSONException {
    List list = new ArrayList();
    for (int i = 0; i < array.length(); i++) {
        list.add(fromJson(array.get(i)));
    }
    return list;
}

From source file:com.vk.sdk.util.VKJsonHelper.java

public static Object toArray(JSONArray array, Class arrayClass) {
    Object ret = Array.newInstance(arrayClass.getComponentType(), array.length());
    Class<?> subType = arrayClass.getComponentType();

    for (int i = 0; i < array.length(); i++) {
        try {/*from w  ww.  j a  v  a  2 s . c  om*/
            Object jsonItem = array.get(i);
            Object objItem = subType.newInstance();
            if (jsonItem instanceof JSONObject) {
                JSONObject jsonItem2 = (JSONObject) jsonItem;
                if (objItem instanceof VKApiModel) {
                    VKApiModel objItem2 = (VKApiModel) objItem;
                    ((VKApiModel) objItem).parse(jsonItem2);
                    Array.set(ret, i, objItem2);
                }
            }
        } catch (JSONException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        } catch (InstantiationException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        } catch (IllegalAccessException e) {
            if (VKSdk.DEBUG)
                e.printStackTrace();
        }
    }
    return ret;
}

From source file:org.apache.cordova.contacts.ContactManager.java

/**
 * Executes the request and returns PluginResult.
 *
 * @param action            The action to execute.
 * @param args              JSONArray of arguments for the plugin.
 * @param callbackContext   The callback context used when calling back into JavaScript.
 * @return                  True if the action was valid, false otherwise.
 *//*from   w ww  .  j  a  v  a  2s . c  o  m*/
public boolean execute(String action, JSONArray args, final CallbackContext callbackContext)
        throws JSONException {

    this.callbackContext = callbackContext;
    this.executeArgs = args;

    /**
     * Check to see if we are on an Android 1.X device.  If we are return an error as we
     * do not support this as of Cordova 1.0.
     */
    if (android.os.Build.VERSION.RELEASE.startsWith("1.")) {
        callbackContext.sendPluginResult(
                new PluginResult(PluginResult.Status.ERROR, ContactManager.NOT_SUPPORTED_ERROR));
        return true;
    }

    /**
     * Only create the contactAccessor after we check the Android version or the program will crash
     * older phones.
     */
    if (this.contactAccessor == null) {
        this.contactAccessor = new ContactAccessorSdk5(this.cordova);
    }

    if (action.equals("search")) {
        final JSONArray filter = args.getJSONArray(0);
        final JSONObject options = args.get(1) == null ? null : args.getJSONObject(1);
        this.cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                JSONArray res = contactAccessor.search(filter, options);
                callbackContext.success(res);
            }
        });
    } else if (action.equals("save")) {
        final JSONObject contact = args.getJSONObject(0);
        this.cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                JSONObject res = null;
                String id = contactAccessor.save(contact);
                if (id != null) {
                    try {
                        res = contactAccessor.getContactById(id);
                    } catch (JSONException e) {
                        Log.e(LOG_TAG, "JSON fail.", e);
                    }
                }
                if (res != null) {
                    callbackContext.success(res);
                } else {
                    callbackContext
                            .sendPluginResult(new PluginResult(PluginResult.Status.ERROR, UNKNOWN_ERROR));
                }
            }
        });
    } else if (action.equals("remove")) {
        final String contactId = args.getString(0);
        this.cordova.getThreadPool().execute(new Runnable() {
            public void run() {
                if (contactAccessor.remove(contactId)) {
                    callbackContext.success();
                } else {
                    callbackContext
                            .sendPluginResult(new PluginResult(PluginResult.Status.ERROR, UNKNOWN_ERROR));
                }
            }
        });
    } else if (action.equals("pickContact")) {
        pickContactAsync();
    } else {
        return false;
    }
    return true;
}

From source file:com.dcs.fakecurrencydetector.MainActivity.java

private void loadJSONData() {
    StringBuffer buffer = new StringBuffer();
    BufferedReader reader = null;
    try {//from   ww w.j  a v a2  s  .co  m
        reader = new BufferedReader(new InputStreamReader(getResources().openRawResource(R.raw.data)));
        String line;
        while ((line = reader.readLine()) != null) {
            buffer.append(line).append("\n");
        }

    } catch (FileNotFoundException e) {
        // TODO exception
    } catch (IOException e) {
        // TODO exception
    } finally {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                // should not happen
            }
        }
    }
    try {
        JSONObject jsonData = new JSONObject(buffer.toString());
        for (Notes note : Notes.values()) {
            String noteValue = note.number + "";
            JSONArray jsonArray = jsonData.getJSONArray(noteValue + "");
            for (int i = 0; i < jsonArray.length(); i++) {
                if (!fakeJSONData.containsKey(noteValue)) {
                    fakeJSONData.put(noteValue, new ArrayList<String>());
                }
                // adding to list
                fakeJSONData.get(noteValue).add(jsonArray.get(i).toString());
            }
        }

    } catch (JSONException e) {
        // TODO exception
    }
}

From source file:org.owasp.goatdroid.fourgoats.rest.searchforfriends.SearchForFriendsResponse.java

static public ArrayList<HashMap<String, String>> parseSearchForFriendsResponse(String response) {

    JSONObject json;//from  ww w.j  a va 2s. c  om
    ArrayList<HashMap<String, String>> results = new ArrayList<HashMap<String, String>>();
    String errors = "";

    try {
        json = new JSONObject(response);
        if (json.getString("success").equals("true")) {
            JSONArray friendArray = json.getJSONArray("users");
            for (int count = 0; count < friendArray.length(); count++) {
                HashMap<String, String> resultsMap = new HashMap<String, String>();
                resultsMap.put("success", "true");
                HashMap<String, String> friend = new HashMap<String, String>();

                if (friendArray.getJSONObject(count).has("userID"))
                    friend.put("userID", (String) friendArray.getJSONObject(count).get("userID"));
                if (friendArray.getJSONObject(count).has("userName"))
                    friend.put("userName", (String) friendArray.getJSONObject(count).get("userName"));
                if (friendArray.getJSONObject(count).has("firstName"))
                    friend.put("firstName", (String) friendArray.getJSONObject(count).get("firstName"));
                if (friendArray.getJSONObject(count).has("lastName"))
                    friend.put("lastName", (String) friendArray.getJSONObject(count).get("lastName"));
                results.add(resultsMap);
                if (friend.size() > 0)
                    results.add(friend);
            }
        } else {
            HashMap<String, String> resultsMap = new HashMap<String, String>();
            resultsMap.put("success", "false");
            try {
                JSONArray errorArray = json.getJSONArray("errors");

                for (int count = 0; count < errorArray.length(); count++)
                    errors += errorArray.getString(count).toString() + "\n\n";

            } catch (JSONException e) {
                errors += json.getString("errors");
            }
            resultsMap.put("errors", errors);
            results.add(resultsMap);
        }
    } catch (JSONException e) {
        try {
            json = new JSONObject(response);
            HashMap<String, String> resultsMap = new HashMap<String, String>();
            resultsMap.put("success", "true");
            results.add(resultsMap);
            HashMap<String, String> friend = new HashMap<String, String>();
            if (json.getJSONObject("users").has("userID"))
                friend.put("userID", (String) json.getJSONObject("users").get("userID"));
            if (json.getJSONObject("users").has("userName"))
                friend.put("userName", (String) json.getJSONObject("users").get("userName"));
            if (json.getJSONObject("users").has("firstName"))
                friend.put("firstName", (String) json.getJSONObject("users").get("firstName"));
            if (json.getJSONObject("users").has("lastName"))
                friend.put("lastName", (String) json.getJSONObject("users").get("lastName"));
            if (friend.size() > 0)
                results.add(friend);

        } catch (JSONException e1) {
            /*
             * We don't care if it falls through here.
             */
            e1.getMessage();
        }
    }
    return results;
}

From source file:screenieup.MixtapeUpload.java

/**
 * Parse the response to get the image link.
 * @param response the image link resulting from the upload
 *///  w  w  w  . j  av  a  2s.c om
private void parseResponse(String response) {
    JSONObject outerjson = new JSONObject(response);
    JSONArray jsnarray = (JSONArray) outerjson.get("files");
    JSONObject innerjson = (JSONObject) jsnarray.get(0);
    mixtapeurl = innerjson.get("url").toString();
}