Example usage for org.json JSONArray getString

List of usage examples for org.json JSONArray getString

Introduction

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

Prototype

public String getString(int index) throws JSONException 

Source Link

Document

Get the string associated with an index.

Usage

From source file:edu.umass.cs.gigapaxos.paxospackets.FindReplicaGroupPacket.java

public FindReplicaGroupPacket(JSONObject msg) throws JSONException {
    super(msg);/*  w w  w.  j  av a  2s  . c  o  m*/
    this.packetType = PaxosPacketType.FIND_REPLICA_GROUP;
    this.nodeID = msg.getInt(PaxosPacket.NodeIDKeys.SNDR.toString());
    JSONArray jsonGroup = null;
    if (msg.has(PaxosPacket.NodeIDKeys.GROUP.toString())) {
        jsonGroup = msg.getJSONArray(PaxosPacket.NodeIDKeys.GROUP.toString());
    }
    if (jsonGroup != null && jsonGroup.length() > 0) {
        this.group = new int[jsonGroup.length()];
        for (int i = 0; i < jsonGroup.length(); i++) {
            this.group[i] = Integer.valueOf(jsonGroup.getString(i));
        }
    } else
        this.group = null;
}

From source file:com.endofhope.neurasthenia.bayeux.BayeuxMessage.java

public BayeuxMessage(String jsonMessage) throws JSONException {
    JSONTokener jsont = new JSONTokener(jsonMessage);
    JSONArray jsona = new JSONArray(jsont);
    // FIXME ? msg   .
    JSONObject jsono = jsona.getJSONObject(0);
    // channel //from  w  w  w  .  j a  v  a 2s .  c o m
    channel = jsono.getString("channel");
    if (channel != null && channel.startsWith("/meta/")) {
        if ("/meta/handshake".equals(channel)) {
            // type 
            type = BayeuxMessage.HANDSHAKE_REQ;
            // version 
            version = jsono.getString("version");
            JSONArray jsonaSupportedConnectionTypes = jsono.getJSONArray("supportedConnectionTypes");
            supportedConnectionTypesList = new ArrayList<String>();
            // supportedConnectionTypes 
            for (int i = 0; i < jsonaSupportedConnectionTypes.length(); i++) {
                supportedConnectionTypesList.add(jsonaSupportedConnectionTypes.getString(i));
            }
            // Handshake req ?  mandatory ? ? ?.
        } else if ("/meta/connect".equals(channel)) {
            type = BayeuxMessage.CONNECT_REQ;
            clientId = jsono.getString("clientId");
            connectionType = jsono.getString("connectionType");
        } else if ("/meta/disconnect".equals(channel)) {
            type = BayeuxMessage.DISCONNECT_REQ;
            clientId = jsono.getString("clientId");
        } else if ("/meta/subscribe".equals(channel)) {
            type = BayeuxMessage.SUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        } else if ("/meta/unsubscribe".equals(channel)) {
            type = BayeuxMessage.UNSUBSCRIBE_REQ;
            clientId = jsono.getString("clientId");
            subscription = jsono.getString("subscription");
        }
    } else {
        type = BayeuxMessage.PUBLISH_REQ;
        data = jsono.getString("data");
    }
}

From source file:com.facebook.internal.BundleJSONConverterTest.java

@Test
public void testSimpleValues() throws JSONException {
    ArrayList<String> arrayList = new ArrayList<String>();
    arrayList.add("1st");
    arrayList.add("2nd");
    arrayList.add("third");

    Bundle innerBundle1 = new Bundle();
    innerBundle1.putInt("inner", 1);

    Bundle innerBundle2 = new Bundle();
    innerBundle2.putString("inner", "2");
    innerBundle2.putStringArray("deep list", new String[] { "7", "8" });

    innerBundle1.putBundle("nested bundle", innerBundle2);

    Bundle b = new Bundle();
    b.putBoolean("boolValue", true);
    b.putInt("intValue", 7);
    b.putLong("longValue", 5000000000l);
    b.putDouble("doubleValue", 3.14);
    b.putString("stringValue", "hello world");
    b.putStringArray("stringArrayValue", new String[] { "first", "second" });
    b.putStringArrayList("stringArrayListValue", arrayList);
    b.putBundle("nested", innerBundle1);

    JSONObject json = BundleJSONConverter.convertToJSON(b);
    assertNotNull(json);/*from ww  w  . j a  v a 2  s .c o m*/

    assertEquals(true, json.getBoolean("boolValue"));
    assertEquals(7, json.getInt("intValue"));
    assertEquals(5000000000l, json.getLong("longValue"));
    assertEquals(3.14, json.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA);
    assertEquals("hello world", json.getString("stringValue"));

    JSONArray jsonArray = json.getJSONArray("stringArrayValue");
    assertEquals(2, jsonArray.length());
    assertEquals("first", jsonArray.getString(0));
    assertEquals("second", jsonArray.getString(1));

    jsonArray = json.getJSONArray("stringArrayListValue");
    assertEquals(3, jsonArray.length());
    assertEquals("1st", jsonArray.getString(0));
    assertEquals("2nd", jsonArray.getString(1));
    assertEquals("third", jsonArray.getString(2));

    JSONObject innerJson = json.getJSONObject("nested");
    assertEquals(1, innerJson.getInt("inner"));
    innerJson = innerJson.getJSONObject("nested bundle");
    assertEquals("2", innerJson.getString("inner"));

    jsonArray = innerJson.getJSONArray("deep list");
    assertEquals(2, jsonArray.length());
    assertEquals("7", jsonArray.getString(0));
    assertEquals("8", jsonArray.getString(1));

    Bundle finalBundle = BundleJSONConverter.convertToBundle(json);
    assertNotNull(finalBundle);

    assertEquals(true, finalBundle.getBoolean("boolValue"));
    assertEquals(7, finalBundle.getInt("intValue"));
    assertEquals(5000000000l, finalBundle.getLong("longValue"));
    assertEquals(3.14, finalBundle.getDouble("doubleValue"), TestUtils.DOUBLE_EQUALS_DELTA);
    assertEquals("hello world", finalBundle.getString("stringValue"));

    List<String> stringList = finalBundle.getStringArrayList("stringArrayValue");
    assertEquals(2, stringList.size());
    assertEquals("first", stringList.get(0));
    assertEquals("second", stringList.get(1));

    stringList = finalBundle.getStringArrayList("stringArrayListValue");
    assertEquals(3, stringList.size());
    assertEquals("1st", stringList.get(0));
    assertEquals("2nd", stringList.get(1));
    assertEquals("third", stringList.get(2));

    Bundle finalInnerBundle = finalBundle.getBundle("nested");
    assertEquals(1, finalInnerBundle.getInt("inner"));
    finalBundle = finalInnerBundle.getBundle("nested bundle");
    assertEquals("2", finalBundle.getString("inner"));

    stringList = finalBundle.getStringArrayList("deep list");
    assertEquals(2, stringList.size());
    assertEquals("7", stringList.get(0));
    assertEquals("8", stringList.get(1));
}

From source file:salvatejero.cordova.liferay.LiferayPlugin.java

public boolean execute(String action, JSONArray args, CallbackContext callbackContext) {

    Log.i(TAG, action);/*  w  w  w.  jav  a 2  s  .co  m*/
    try {
        if (ACTION_CONNECT.equals(action)) {
            String userName = args.getString(1);
            String serverIp = args.getString(0);
            String password = args.getString(2);

            doConnect(callbackContext, serverIp, userName, password);
            return true;

        } else if (GET_CONNECT.equals(action)) {
            String classNameId = args.getString(0);
            getObjectModel(callbackContext, classNameId, args.getString(1), args.getJSONArray(2));
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        callbackContext.error("Params error");
        Log.e(TAG, "Params error");
        return false;
    }
}

From source file:salvatejero.cordova.liferay.LiferayPlugin.java

private Object[] getListOfParam(Method m, JSONArray values) throws JSONException {
    List<Object> listOfParams = new ArrayList<Object>();
    for (int i = 0; i < m.getParameterTypes().length; i++) {
        @SuppressWarnings("rawtypes")
        Class c = m.getParameterTypes()[i];
        if (c.getName().equals("java.lang.String")) {
            listOfParams.add(values.getString(i));
        } else if (c.getName().equals("java.lang.Long")) {
            listOfParams.add(values.getLong(i));
        } else if (c.getName().equals("java.lang.Integer")) {
            listOfParams.add(values.getInt(i));
        } else if (c.getName().equals("long")) {
            listOfParams.add(values.getLong(i));
        } else if (c.getName().equals("int")) {
            listOfParams.add(values.getInt(i));
        }/*from w  w  w  .j a va2 s. co  m*/
    }
    Object[] paramsA = new Object[listOfParams.size()];
    return listOfParams.toArray(paramsA);
}

From source file:com.google.enterprise.connector.ldap.LdapConnectorConfig.java

/**
 * Gets the attribute which has the appended schema attributes and splits them
 * to add individual items in the provided set.
 * @param config Config of user entered entries
 * @param tempSchema Set which holds the schema attributes.
 *//* w ww .  ja  v a 2  s  .  com*/
private void addSchemaFromConfig(Map<String, String> config, Set<String> tempSchema) {

    String schemaValues = getJsonStringForSelectedAttributes(config);
    if (schemaValues != null && schemaValues.trim().length() != 0) {
        JSONArray arr;
        try {
            arr = new JSONArray(schemaValues);
            for (int i = 0; i < arr.length(); i++) {
                tempSchema.add(arr.getString(i));
            }
        } catch (JSONException e) {
            LOG.warning("Did not get any selected attributes...");
        }
    }
    LOG.fine("Selected attributes: " + tempSchema);
}

From source file:com.cranberrygame.cordova.plugin.optionsmenu.OptionsMenu.java

@Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
    //args.length()
    //args.getString(0)
    //args.getString(1)
    //args.Int(0)
    //args.Int(1)
    //args.getBoolean(0)
    //args.getBoolean(1)

    if (action.equals("setUp")) {
        callbackContextKeepCallback = callbackContext;
    } else if (action.equals("setMenus")) {
        //Activity activity=cordova.getActivity();
        //webView         
        String menus = args.getString(0);
        Log.d("Menu", menus);

        this.menus = menus;
    } else if (action.equals("showMenus")) {
        //Activity activity=cordova.getActivity();
        //webView         

        cordova.getActivity().openOptionsMenu();
    }//w  w  w.  j a va  2 s. co  m

    return true;
}

From source file:edu.umass.cs.msocket.common.policies.GeolocationProxyPolicy.java

/**
 * @throws Exception if a GNS error occurs
 * @see edu.umass.cs.msocket.common.policies.ProxySelectionPolicy#getNewProxy()
 *//*w  w w.jav a  2 s  .c o m*/
@Override
public List<InetSocketAddress> getNewProxy() throws Exception {
    // Lookup for active location service GUIDs
    final UniversalGnsClient gnsClient = gnsCredentials.getGnsClient();
    final GuidEntry guidEntry = gnsCredentials.getGuidEntry();
    JSONArray guids;
    try {
        guids = gnsClient.fieldRead(proxyGroupName, GnsConstants.ACTIVE_LOCATION_FIELD, guidEntry);
    } catch (Exception e) {
        throw new GnsException("Could not find active location services (" + e + ")");
    }

    // Try every location proxy in the list until one works
    for (int i = 0; i < guids.length(); i++) {
        // Retrieve the location service IP and connect to it
        String locationGuid = guids.getString(i);
        String locationIP = gnsClient.fieldRead(locationGuid, GnsConstants.LOCATION_SERVICE_IP, guidEntry)
                .getString(0);
        logger.fine("Contacting location service " + locationIP + " to request " + numProxies + " proxies");

        // Location IP is stored as host:port
        StringTokenizer st = new StringTokenizer(locationIP, ":");
        try {
            // Protocol is send the number of desired proxies and receive strings
            // containing proxy IP:port
            Socket s = new Socket(st.nextToken(), Integer.parseInt(st.nextToken()));
            ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
            oos.writeInt(numProxies);
            oos.flush();
            List<InetSocketAddress> result = new LinkedList<InetSocketAddress>();
            while (!s.isClosed() && result.size() < numProxies) {
                String proxyIP = ois.readUTF();
                StringTokenizer stp = new StringTokenizer(proxyIP, ":");
                result.add(new InetSocketAddress(stp.nextToken(), Integer.parseInt(stp.nextToken())));
            }
            if (!s.isClosed()) // We receive all the proxies we need, just close the
                               // socket
                s.close();
            return result;
        } catch (Exception e) {
            logger.info("Failed to obtain proxy from location service" + locationIP + " (" + e + ")");
        }
    }

    throw new GnsException("Could not find any location service to provide a geolocated proxy");
}

From source file:census.couchdroid.CouchViewResults.java

/**
 * Retrieves a list of documents that matched this View.
 * These documents only contain the data that the View has returned (not the full document).
 * <p>//from   w  w w .  jav  a2s.c  o  m
 * You can load the remaining information from Document.reload();
 * 
 * @return
*/
public List<CouchDocument> getResults() {
    JSONArray ar = null;
    try {
        android.util.Log.e("Census", getJSONObject().toString());
        ar = getJSONObject().getJSONArray("rows");
    } catch (JSONException e) {
        return null;
    }
    List<CouchDocument> docs = new ArrayList<CouchDocument>(ar.length());
    for (int i = 0; i < ar.length(); i++) {
        try {
            if (ar.get(i) != null && !ar.getString(i).equals("null")) {
                CouchDocument d = new CouchDocument(ar.getJSONObject(i));
                d.setDatabase(database);
                docs.add(d);
            }
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return docs;

}

From source file:ub.botiga.data.User.java

public User(JSONObject obj, HashMap<String, Product> totalproducts) throws JSONException {
    this.mName = obj.getString("name");
    this.mCredit = (float) obj.getDouble("credit");
    this.mProducts = new HashMap<String, Product>();
    JSONArray m = obj.getJSONArray("products");
    String p;/*from w ww . j av a  2  s  .  co  m*/
    for (int i = 0; i < m.length(); i++) {
        p = m.getString(i);
        if (totalproducts.containsKey(p)) {
            mProducts.put(p, totalproducts.get(p));
        }
    }

}