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.tapfortap.phonegap.TapForTapPhoneGapPlugin.java

@Override
public PluginResult execute(String action, JSONArray arguments, String callbackId) {
    PluginResult result = null;/*from   w  w w  .ja  va  2  s  .c  o m*/

    Object firstArg = null;
    if (arguments.length() > 0) {
        try {
            firstArg = arguments.get(0);
        } catch (JSONException e) {
            Log.e(TAG, e.getLocalizedMessage(), e);
            return new PluginResult(Status.ERROR);
        }
    }

    try {
        Log.d(TAG, "Action " + action + ", arguments: " + arguments);
        if (action.equals("initializeWithAPIKey")) {
            result = initialize((String) firstArg);
        } else if (action.equals("createAdView")) {
            result = createAdView((JSONObject) firstArg);
        } else if (action.equals("loadAds")) {
            result = loadAds((JSONObject) firstArg);
        } else if (action.equals("moveAdView")) {
            result = moveAdView((JSONObject) firstArg);
        } else if (action.equals("removeAdView")) {
            result = removeAdView();
        } else if (action.equals("prepareInterstitial")) {
            result = prepareInterstitial();
        } else if (action.equals("showInterstitial")) {
            result = showInterstitial();
        } else if (action.equals("prepareAppWall")) {
            result = prepareAppWall();
        } else if (action.equals("showAppWall")) {
            result = showAppWall();
        } else {
            Log.w(TAG, "Unknown action " + action + ", arguments: " + arguments);
        }
    } catch (JSONException e) {
        Log.e(TAG, e.getLocalizedMessage(), e);
        result = new PluginResult(Status.JSON_EXCEPTION);
    }

    return result;
}

From source file:io.github.grahambell.taco.TacoTransport.java

/**
 * Convert JSON array to Java List.//from  w  w  w. jav  a  2s . c  o  m
 *
 * Each entry in the object is converted using the {@link #jsonToObject}
 * method.
 *
 * @param json the JSON array
 * @return Java List representation of the array
 * @throws TacoException on error in conversion
 */
public List<Object> jsonToList(JSONArray json) throws TacoException {
    List<Object> list = new ArrayList<Object>();

    for (int i = 0; i < json.length(); i++) {
        list.add(jsonToObject(json.get(i)));
    }

    return list;
}

From source file:vOS.controller.socket.IOConnection.java

/**
 * Transport message. {@link IOTransport} calls this, when a message has
 * been received./*from ww w. j a  va 2s. co  m*/
 * 
 * @param text
 *            the text
 */
public void transportMessage(String text) {
    logger.info("< " + text);
    IOMessage message;
    try {
        message = new IOMessage(text);
    } catch (Exception e) {
        error(new SocketIOException("Garbage from server: " + text, e));
        return;
    }
    resetTimeout();
    switch (message.getType()) {
    case IOMessage.TYPE_DISCONNECT:
        try {
            findCallback(message).onDisconnect();
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onDisconnect()", e));
        }
        break;
    case IOMessage.TYPE_CONNECT:
        try {
            if (firstSocket != null && "".equals(message.getEndpoint())) {
                if (firstSocket.getNamespace().equals("")) {
                    firstSocket.getCallback().onConnect();
                } else {
                    IOMessage connect = new IOMessage(IOMessage.TYPE_CONNECT, firstSocket.getNamespace(), "");
                    sendPlain(connect.toString());
                }
            } else {
                findCallback(message).onConnect();
            }
            firstSocket = null;
        } catch (Exception e) {
            error(new SocketIOException("Exception was thrown in onConnect()", e));
        }
        break;
    case IOMessage.TYPE_HEARTBEAT:
        sendPlain("2::");
        break;
    case IOMessage.TYPE_MESSAGE:
        try {
            findCallback(message).onMessage(message.getData(), remoteAcknowledge(message));
        } catch (Exception e) {
            error(new SocketIOException(
                    "Exception was thrown in onMessage(String).\n" + "Message was: " + message.toString(), e));
        }
        break;
    case IOMessage.TYPE_JSON_MESSAGE:
        try {
            JSONObject obj = null;
            String data = message.getData();
            if (data.trim().equals("null") == false)
                obj = new JSONObject(data);
            try {
                findCallback(message).onMessage(obj, remoteAcknowledge(message));
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in onMessage(JSONObject).\n" + "Message was: "
                        + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;
    case IOMessage.TYPE_EVENT:
        try {
            JSONObject event = new JSONObject(message.getData());
            Object[] argsArray;
            if (event.has("args")) {
                JSONArray args = event.getJSONArray("args");
                argsArray = new Object[args.length()];
                for (int i = 0; i < args.length(); i++) {
                    if (args.isNull(i) == false)
                        argsArray[i] = args.get(i);
                }
            } else
                argsArray = new Object[0];
            String eventName = event.getString("name");
            try {
                findCallback(message).on(eventName, remoteAcknowledge(message), argsArray);
            } catch (Exception e) {
                error(new SocketIOException("Exception was thrown in on(String, JSONObject[]).\n"
                        + "Message was: " + message.toString(), e));
            }
        } catch (JSONException e) {
            logger.warning("Malformated JSON received");
        }
        break;

    case IOMessage.TYPE_ACK:
        String[] data = message.getData().split("\\+", 2);
        if (data.length == 2) {
            try {
                int id = Integer.parseInt(data[0]);
                IOAcknowledge ack = acknowledge.get(id);
                if (ack == null)
                    logger.warning("Received unknown ack packet");
                else {
                    JSONArray array = new JSONArray(data[1]);
                    Object[] args = new Object[array.length()];
                    for (int i = 0; i < args.length; i++) {
                        args[i] = array.get(i);
                    }
                    ack.ack(args);
                }
            } catch (NumberFormatException e) {
                logger.warning(
                        "Received malformated Acknowledge! This is potentially filling up the acknowledges!");
            } catch (JSONException e) {
                logger.warning("Received malformated Acknowledge data!");
            }
        } else if (data.length == 1) {
            sendPlain("6:::" + data[0]);
        }
        break;
    case IOMessage.TYPE_ERROR:
        try {
            findCallback(message).onError(new SocketIOException(message.getData()));
        } catch (SocketIOException e) {
            error(e);
        }
        if (message.getData().endsWith("+0")) {
            // We are advised to disconnect
            cleanup();
        }
        break;
    case IOMessage.TYPE_NOOP:
        break;
    default:
        logger.warning("Unkown type received" + message.getType());
        break;
    }
}

From source file:griffon.plugins.preferences.persistors.JsonPreferencesPersistor.java

@Nonnull
private Collection expand(@Nonnull JSONArray array) {
    List<Object> list = new ArrayList<>();
    for (int i = 0; i < array.length(); i++) {
        Object element = array.get(i);
        if (element instanceof Number || element instanceof Boolean || element instanceof CharSequence) {
            list.add(element);/*from   ww  w  . j  av a2  s .  c  o  m*/
        } else {
            throw new IllegalArgumentException("Invalid value: " + element);
        }
    }

    return list;
}

From source file:fyp.project.S_File.S_Activities.java

public void doWay(String server_output) {
    /*        tvOutput.setText(Environment.getExternalStorageDirectory() + "/DCIM/Camera/a.mp4");*/

    JSONArray array = null;
    List<String> list_output = new ArrayList<String>();
    String output = server_output;
    if (!output.equals("[]")) {

        Logger.getLogger(S_Login.class.getName()).info("true...............");
        try {//ww w. j av a 2  s.  c o m
            array = new JSONArray(server_output);
        } catch (JSONException ex) {
            Logger.getLogger(S_Login.class.getName()).log(Level.SEVERE, null, ex);
        }

        for (int n = 0; n < array.length(); n++) {
            String temp = "";
            for (int m = 0; m < 3; m++) {
                try {
                    output += " " + array.getJSONArray(n).get(m).toString() + "\n ";
                    temp += " " + array.getJSONArray(n).get(m).toString() + "\n ";
                } catch (JSONException ex) {
                    Logger.getLogger(S_Login.class.getName()).log(Level.SEVERE, null, ex);

                }
            }

            list_output.add(temp);
            output += "\n";
        }
        aryAdapter_list = new ArrayAdapter(activity, android.R.layout.simple_list_item_1, list_output);
        gv.setAdapter(aryAdapter_list);
        Logger.getLogger(S_Login.class.getName()).info(output);

    } else {
        EditText edit_username = (EditText) activity.findViewById(R.id.edit_username);
        EditText edit_password = (EditText) activity.findViewById(R.id.edit_password);
        if (output.equals("[]")) {
            tvOutput.setText("Please Login Again" + server_output);
            edit_username.setText("");
            edit_password.setText("");
        } else {
            tvOutput.setText("Page Not Found 404" + server_output);
        }
        /*AlertDialog.Builder MyAlertDialog = new AlertDialog.Builder(activity);
         MyAlertDialog.setTitle("Login Fail");
         MyAlertDialog.setMessage("Please Login Again");
         MyAlertDialog.show();
                 
         */

    }

    mProgressDialog.dismiss();

}

From source file:org.upv.satrd.fic2.fe.connectors.citySDK.Fusion.java

public static FusionResult fusion(JSONObject poi1, JSONObject poi2, FusionRule fr, Logger log) {

    FusionResult fusionresult = null;//from ww  w .j  a  va2 s  .  co  m
    String name_source = "";
    if (log == null)
        log = Fusion.log;

    try {

        int namePos1 = CommonUtils.getPropertyPos(poi1, "name", log);
        String source1 = poi1.getJSONArray("label").getJSONObject(namePos1).getString("base");
        int namePos2 = CommonUtils.getPropertyPos(poi2, "name", log);
        String source2 = poi2.getJSONArray("label").getJSONObject(namePos2).getString("base");

        //Fusion label tag
        JSONArray object1 = poi1.getJSONArray("label");
        JSONArray object2 = poi2.getJSONArray("label");

        JSONArray object3 = new JSONArray();
        int i = 0;

        //TODO we are not combining the location.address element of both POIs. Now we just take the first one (the one that conditions position)   

        //////////////////////
        //Add name. We take the one that first appears in the name ArrayList
        //////////////////////
        for (int j = 0; j < fr.getName().size(); j++) {
            if (fr.getName().get(j).equals(source1)) {
                int namePos = CommonUtils.getPropertyPos(poi1, "name", log);
                object3.put(i, poi1.getJSONArray("label").getJSONObject(namePos));
                i++;
                log.info("Fusion.fusion(). Fusioning. Inserting name from source: " + source1);
                name_source = source1;
                break;
            }
            if (fr.getName().get(j).equals(source2)) {
                int namePos = CommonUtils.getPropertyPos(poi2, "name", log);
                object3.put(i, poi2.getJSONArray("label").getJSONObject(namePos));
                log.info("Fusion.fusion(). Fusioning. Inserting name from source: " + source2);
                name_source = source2;
                i++;
                break;
            }
        }

        ////////////////////
        //Add other labels
        ////////////////////
        ArrayList<String> allObjects = new ArrayList<String>();

        for (int j = 0; j < object1.length(); j++) {
            //If is not name
            if (!poi1.getJSONArray("label").getJSONObject(j).get("term").equals("name")) {
                String value = (String) poi1.getJSONArray("label").getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, poi1.getJSONArray("label").getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }

        }
        for (int j = 0; j < object2.length(); j++) {
            //If is not name
            if (!poi2.getJSONArray("label").getJSONObject(j).get("term").equals("name")) {
                String value = (String) poi2.getJSONArray("label").getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, poi2.getJSONArray("label").getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        //We'll store the final POI in poi1. We preserve the structure and override step by step. Up to now only label
        poi1.put("label", object3);

        ///////////////////////////////////
        //Fusion description tag. It is possible that this tag does not appear in some POIs, so we must be careful 
        //////////////////////////////////
        try {
            object1 = poi1.getJSONArray("description");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source1
                    + " does not have description. We'll take the description from the other POI independently of the FusionRule");
        }
        try {
            object2 = poi2.getJSONArray("description");
        } catch (JSONException e) {
            object2 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source2
                    + " does not have description. We'll take the description from the other POI independently of the FusionRule");
        }

        object3 = new JSONArray();
        i = 0;

        if (object1 == null) {
            object3.put(i, poi2.getJSONArray("description").getJSONObject(i));
        } else {
            if (object2 == null) {
                object3.put(i, poi1.getJSONArray("description").getJSONObject(i));
            } else {

                for (int j = 0; j < fr.getDescription().size(); j++) {
                    if (fr.getDescription().get(j).equals(source1)) {
                        if (poi1.getJSONArray("description").length() > 0) {
                            object3.put(i, poi1.getJSONArray("description").getJSONObject(i));
                            log.info("Fusion.fusion(). Fusioning. Inserting description from source: "
                                    + source1);
                            break;
                        }
                    }
                    if (fr.getDescription().get(j).equals(source2)) {
                        if (poi2.getJSONArray("description").length() > 0) {
                            object3.put(i, poi2.getJSONArray("description").getJSONObject(i));
                            log.info(
                                    "Fusion.fusion().Fusioning. Inserting description from source: " + source2);
                            break;
                        }
                    }
                }
            }
        }

        //Override description field
        poi1.put("description", object3);

        //////////////////////////
        //Fusion category tag
        /////////////////////////
        try {
            object1 = poi1.getJSONArray("category");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source1
                    + " does not have category.");
        }
        try {
            object2 = poi2.getJSONArray("category");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion(). Fusioning. POI object from source " + source2
                    + " does not have category.");
        }

        allObjects = new ArrayList<String>(); //We don't need it as we will add all categories, we'll not check if they are repeated   
        object3 = new JSONArray();
        i = 0;

        if (object1 == null) {
            object3.put(i, poi2.getJSONArray("category").getJSONObject(i));
        } else {
            if (object2 == null) {
                object3.put(i, poi1.getJSONArray("category").getJSONObject(i));
            } else {

                for (int j = 0; j < object1.length(); j++) {
                    String value = (String) object1.getJSONObject(j).get("value");

                    object3.put(i, object1.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
                for (int j = 0; j < object2.length(); j++) {
                    String value = (String) object2.getJSONObject(j).get("value");

                    object3.put(i, object2.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }

            }
        }

        //Override category
        poi1.put("category", object3);

        ///////////////////////////
        //Fusion link tag
        ///////////////////////////
        try {
            object1 = poi1.getJSONArray("link");
        } catch (JSONException e) {
            object1 = null;
            log.warn("Fusion.fusion().Fusioning. POI object from source " + source1 + " does not have link.");
        }
        try {
            object2 = poi2.getJSONArray("link");

        } catch (JSONException e) {
            object2 = null;
            log.warn("Fusion.fusion().Fusioning. POI object from source " + source2 + " does not have link.");
        }

        allObjects = new ArrayList<String>();

        object3 = new JSONArray();
        i = 0;

        if (object1 != null) {
            for (int j = 0; j < object1.length(); j++) {
                String value = (String) object1.getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, object1.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        if (object2 != null) {
            for (int j = 0; j < object2.length(); j++) {
                String value = (String) object2.getJSONObject(j).get("value");
                //If is not repeated
                if (!allObjects.contains(value)) {
                    object3.put(i, object2.getJSONObject(j));
                    allObjects.add(value);
                    i++;
                }
            }
        }

        //Override link
        poi1.put("link", object3);

        //Finally we should override the publisher part to say 'Fusion Engine'. Anyway we can set it up during the storage of the POI in the database

        //Create the FusionResult return object
        fusionresult = new FusionResult(poi1, name_source);

    } catch (Exception e) {
        System.out.println("Error.Fusion.fusion(): " + e.getMessage());
        log.error("Error.Fusion.fusion(): " + e.getMessage());
    }

    return fusionresult;

}

From source file:com.easy.facebook.android.apicall.RestApi.java

public List<String> getFriendUIDs() throws EasyFacebookError {

    Bundle params = new Bundle();
    params.putString("format", "json");
    params.putString("method", "friends.get");
    params.putString("access_token", facebook.getAccessToken());

    String jsonResponse;/*from ww  w  . j av a  2  s.c  o  m*/
    List<String> stringList = new ArrayList<String>();

    try {
        jsonResponse = Util.openUrl("https://api.facebook.com/restserver.php", "POST", params);

        JSONArray jsonArray = new JSONArray(jsonResponse);

        for (int i = 0; i < jsonArray.length(); i++)
            stringList.add(jsonArray.get(i).toString().replaceAll("\"", ""));

    } catch (MalformedURLException e) {

        throw new EasyFacebookError(e.toString(), "MalformedURLException");
    } catch (IOException e) {

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

        throw new EasyFacebookError(e.toString(), "JSONException");
    }

    return stringList;
}

From source file:org.collectionspace.chain.csp.webui.record.RecordSearchList.java

private boolean morePermissions(JSONObject permissionResults, String key) throws JSONException {
    boolean result = false;

    if (permissionResults.has("pagination")) {
        JSONObject pagination = permissionResults.getJSONObject("pagination");
        JSONArray separatelists = pagination.getJSONArray("separatelists");
        String[] permissionsList = (String[]) separatelists.get(0);
        //// w ww .  j  a va 2 s .  c o m
        // If the permissionsList is not empty then there still might
        // be another page of permissions, so we'll return true
        //
        if (permissionsList != null && permissionsList.length > 0) {
            result = true;
        }
    }
    //
    // Just to be safe, we'll also return true if we found items in the result list.
    //
    if (permissionResults.has(key) && permissionResults.getJSONArray(key).length() > 0) {
        result = true;
    }

    return result;
}

From source file:com.pimp.companionforband.utils.jsontocsv.parser.JsonFlattener.java

private void flatten(JSONArray obj, Map<String, String> flatJson, String prefix) {
    int length = obj.length();
    for (int i = 0; i < length; i++) {
        try {//  www .  j  a  v a2 s.  c o  m
            if (obj.get(i).getClass() == JSONArray.class) {
                JSONArray jsonArray = (JSONArray) obj.get(i);
                if (jsonArray.length() < 1)
                    continue;
                flatten(jsonArray, flatJson, prefix + i);
            } else if (obj.get(i).getClass() == JSONObject.class) {
                JSONObject jsonObject = (JSONObject) obj.get(i);
                flatten(jsonObject, flatJson, prefix + (i + 1));
            } else {
                String value = obj.getString(i);
                if (value != null)
                    flatJson.put(prefix + (i + 1), value);
            }
        } catch (Exception e) {
            Log.e("flattenJsonArray", e.toString());
        }
    }
}

From source file:com.dimasdanz.kendalipintu.usermodel.UserLoadData.java

@Override
protected List<UserModel> doInBackground(String... args) {
    List<UserModel> userList = new ArrayList<UserModel>();
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    JSONObject json = jsonParser.makeHttpRequest(ServerUtilities.getUserListUrl(activity) + current_page, "GET",
            params);//from w  w w  .jav a2 s  . c o  m
    if (json != null) {
        try {
            if (json.getInt("response") == 1) {
                JSONArray userid = json.getJSONArray("userid");
                JSONArray username = json.getJSONArray("username");
                JSONArray userpass = json.getJSONArray("userpass");
                for (int i = 0; i < userid.length(); i++) {
                    userList.add(new UserModel(userid.get(i).toString(), username.get(i).toString(),
                            userpass.getString(i).toString()));
                }
                return userList;
            } else {
                return null;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            return null;
        }
    } else {
        con = false;
        return null;
    }
}