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.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

private static JSONArray addRepeatedNodeToJson(Element container, Repeat f, String permlevel,
        JSONObject tempSon) throws JSONException {
    JSONArray node = new JSONArray();
    List<FieldSet> children = getChildrenWithGroupFields(f, permlevel);
    JSONArray elementlist = extractRepeatData(container, f, permlevel);

    JSONObject siblingitem = new JSONObject();
    for (int i = 0; i < elementlist.length(); i++) {
        JSONObject element = elementlist.getJSONObject(i);

        Iterator<?> rit = element.keys();
        while (rit.hasNext()) {
            String key = (String) rit.next();
            JSONArray arrvalue = new JSONArray();
            for (FieldSet fs : children) {

                if (fs instanceof Repeat && ((Repeat) fs).hasServicesParent()) {
                    if (!((Repeat) fs).getServicesParent()[0].equals(key)) {
                        continue;
                    }/* w w  w . j av  a2 s.com*/
                    Object value = element.get(key);
                    arrvalue = (JSONArray) value;
                } else {
                    if (!fs.getID().equals(key)) {
                        continue;
                    }
                    Object value = element.get(key);
                    arrvalue = (JSONArray) value;
                }

                if (fs instanceof Field) {
                    for (int j = 0; j < arrvalue.length(); j++) {
                        JSONObject repeatitem = new JSONObject();
                        //XXX remove when service layer supports primary tags
                        if (f.hasPrimary() && j == 0) {
                            repeatitem.put("_primary", true);
                        }
                        Element child = (Element) arrvalue.get(j);
                        Object val = child.getText();
                        Field field = (Field) fs;
                        String id = field.getID();
                        if (f.asSibling()) {
                            addExtraToJson(siblingitem, child, field, tempSon);
                            if (field.getDataType().equals("boolean")) {
                                siblingitem.put(id, (Boolean.parseBoolean((String) val) ? true : false));
                            } else {
                                siblingitem.put(id, val);
                            }
                        } else {
                            addExtraToJson(repeatitem, child, field, tempSon);
                            if (field.getDataType().equals("boolean")) {
                                repeatitem.put(id, (Boolean.parseBoolean((String) val) ? true : false));
                            } else {
                                repeatitem.put(id, val);
                            }
                            node.put(repeatitem);
                        }

                        tempSon = addtemp(tempSon, fs.getID(), child.getText());
                    }
                } else if (fs instanceof Group) {
                    JSONObject tout = new JSONObject();
                    JSONObject tempSon2 = new JSONObject();
                    Group rp = (Group) fs;
                    addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", "");

                    if (f.asSibling()) {
                        JSONArray a1 = tout.getJSONArray(rp.getID());
                        JSONObject o1 = a1.getJSONObject(0);
                        siblingitem.put(fs.getID(), o1);
                    } else {
                        JSONObject repeatitem = new JSONObject();
                        repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID()));
                        node.put(repeatitem);
                    }

                    tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID()));
                    //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString());
                } else if (fs instanceof Repeat) {
                    JSONObject tout = new JSONObject();
                    JSONObject tempSon2 = new JSONObject();
                    Repeat rp = (Repeat) fs;
                    addRepeatToJson(tout, container, rp, permlevel, tempSon2, "", "");

                    if (f.asSibling()) {
                        siblingitem.put(fs.getID(), tout.getJSONArray(rp.getID()));
                    } else {
                        JSONObject repeatitem = new JSONObject();
                        repeatitem.put(fs.getID(), tout.getJSONArray(rp.getID()));
                        node.put(repeatitem);
                    }

                    tempSon = addtemp(tempSon, rp.getID(), tout.getJSONArray(rp.getID()));
                    //log.info(f.getID()+":"+rp.getID()+":"+tempSon.toString());
                }
            }
        }
    }

    if (f.asSibling()) {
        node.put(siblingitem);
    }
    return node;
}

From source file:game.Clue.ClueGameUI.java

private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
    // TODO add your handling code here:
    //Move Button Pressed

    // check game-state to determine available moves
    //new JSONObject("{"players":[{"position":"0,3","name":null,"active":"true","cards":"MR GREEN,CANDLESTICK,BALLROOM","character":"scarlet"},{"position":"1,4","name":null,"active":"true","cards":"PROFESSOR PLUM,BILLARD ROOM,ROPE","character":"mustard"},{"position":"4,3","name":null,"active":"true","cards":"DINING ROOM,REVOLVER,WRENCH","character":"white"},{"position":"4,1","name":null,"active":"true","cards":"LIBRARY,COLONEL MUSTARD,STUDY","character":"green"},{"position":"3,0","name":null,"active":"true","cards":"MISS SCARLET,MRS PEACOCK,KNIFE","character":"peacock"},{"position":"1,0","name":null,"active":"true","cards":"HALL,CONSERVATORY,LOUNGE","character":"plum"}],"move_state":{"player":"scarlet","moves":[["[0,4, 0,2]","accusation"]]},"winner":null}");
    try {//from  w w w . j  a  v  a 2  s  .c  om
        JSONArray available_moves;
        //String available_moves;
        String[] available_moves_array;
        Object[] available_moves_object = null;
        available_moves = player_connection.currentgame_state.getJSONObject("move_state").getJSONArray("moves");
        //available_moves_array = available_moves.split("]");
        System.out.println(available_moves.length());
        for (int i = 0; i < available_moves.length(); i++) {
            System.out.println(available_moves.get(i));
            //available_moves_object[i] = 
        }
        //String m = (String) JOptionPane.showInputDialog(this, "Where would you live to move?", "Select your move", JOptionPane.PLAIN_MESSAGE, null, available_moves_object, "");
    } catch (JSONException ex) {
        Logger.getLogger(ClueGameUI.class.getName()).log(Level.SEVERE, null, ex);
    }

    //let user select which room ,from options presented, to move into
    //update server with new players location
}

From source file:game.Clue.ClueGameUI.java

private void initializeMyHand() {
    //get player's hand from game state data
    JSONArray card_hand;
    String[] card_hand_object = null;
    try {/*from   ww w .j  av  a  2  s  . c o  m*/
        card_hand = player_connection.currentgame_state.getJSONArray("players")
                .getJSONObject(player_connection.game_slot).getJSONArray("cards");
        for (int i = 0; i < card_hand.length(); i++) {
            card_hand_object[i] = card_hand.get(i).toString();

        }
        mycard1.setText(card_hand_object[1]); //card 1
        mycard2.setText(card_hand_object[2]); //card 2
        mycard3.setText(card_hand_object[3]); //card 3
        System.out.println(mycard1.getText());
        System.out.println(mycard2.getText());
        System.out.println(mycard3.getText());
    } catch (JSONException ex) {
        Logger.getLogger(ClueGameUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    // player.connection.currentgame_state.

}

From source file:org.jabsorb.ng.serializer.impl.RawJSONArraySerializer.java

@Override
public Object marshall(final SerializerState state, final Object p, final Object o) throws MarshallException {

    // reprocess the raw json in order to fixup circular references and
    // duplicates
    final JSONArray jsonIn = (JSONArray) o;
    final JSONArray jsonOut = new JSONArray();

    int i = 0;/*from   ww  w.  j  av  a 2  s .  c o m*/
    try {
        final int j = jsonIn.length();

        for (i = 0; i < j; i++) {
            final Object json = ser.marshall(state, o, jsonIn.get(i), new Integer(i));
            if (JSONSerializer.CIRC_REF_OR_DUPLICATE != json) {
                jsonOut.put(i, json);
            } else {
                // put a slot where the object would go, so it can be fixed
                // up properly in the fix up phase
                jsonOut.put(i, JSONObject.NULL);
            }
        }
    } catch (final MarshallException e) {
        throw new MarshallException("element " + i, e);
    } catch (final JSONException e) {
        throw new MarshallException("element " + i, e);
    }
    return jsonOut;
}

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. j a va  2 s . 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:com.aerhard.oxygen.plugin.dbtagger.util.JsonUtil.java

/**
 * Gets table headers from the JSON server response.
 * /*from   w ww . j a  v  a 2  s .c  om*/
 * @param responseJSON
 *            the JSON response
 * @return the headers
 */
private String[] getTableHeaders(JSONObject responseJSON) {
    String[] cols = null;
    try {
        JSONArray colsArray = responseJSON.getJSONArray("cols");
        cols = new String[colsArray.length()];
        JSONObject fieldObj;
        for (int i = 0; i < colsArray.length(); i++) {
            fieldObj = (JSONObject) colsArray.get(i);
            cols[i] = fieldObj.optString("name");
        }
    } catch (JSONException e) {
        workspace.showErrorMessage(i18n.getString("jsonUtil.columnNameError"));
    }
    return cols;
}

From source file:es.prodevelop.gvsig.mini.json.GeoJSONParser.java

private double[] decodeCoordinates(JSONArray coordinates) throws JSONException {

    double[] coords = new double[2];
    int size = coordinates.length();
    for (int i = 0; i < size; i++) {
        coords[i] = Double.parseDouble(coordinates.get(i).toString());
    }// ww  w . j  a  va 2s  .co m
    return coords;
}

From source file:org.wso2.carbon.connector.integration.test.meetup.venues.VenuesIntegrationTest.java

@Test(groups = { "wso2.esb" }, description = "meetup {getRecommendedVenues} integration test")
public void testGetRecommendedVenuesWithOptionalParameters() throws Exception {

    String jsonRequestFilePath = pathToRequestsDirectory + "venues_getRecommendedVenues_optional.txt";
    String methodName = "venues_get_recommended_venues";

    final String jsonString = ConnectorIntegrationUtil.getFileContent(jsonRequestFilePath);
    final String proxyFilePath = "file:///" + pathToProxiesDirectory + methodName + ".xml";
    String modifiedJsonString = String.format(jsonString, meetupConnectorProperties.getProperty("key"));
    proxyAdmin.addProxyService(new DataHandler(new URL(proxyFilePath)));

    try {//from   w  w  w. j  a v a  2  s  .  c  o m

        JSONArray jsonObjectArray = ConnectorIntegrationUtil
                .sendRequestJSONArray(getProxyServiceURL(methodName), modifiedJsonString);

        JSONObject jsonObject = (JSONObject) jsonObjectArray.get(0);
        Assert.assertTrue(jsonObject.has("visibility"));

    } finally {
        proxyAdmin.deleteProxy(methodName);
    }
}

From source file:com.sublimis.urgentcallfilter.Magic.java

public static JSONArray jsonArrayRemove(JSONArray jsonArray, int index) {
    JSONArray newJsonArray = jsonArray;/*ww w .jav a  2  s .  c om*/

    if (jsonArray != null) {
        newJsonArray = new JSONArray();
        int len = jsonArray.length();

        for (int i = 0; i < len; i++) {
            // Excluding the item at position
            if (i != index) {
                try {
                    newJsonArray.put(jsonArray.get(i));
                } catch (Exception e) {
                }
            }
        }
    }

    return newJsonArray;
}

From source file:org.jabsorb.ng.serializer.impl.SetSerializer.java

@Override
public ObjectMatch tryUnmarshall(final SerializerState state, final Class<?> clazz, final Object o)
        throws UnmarshallException {

    JSONArray jsonset;
    if (o instanceof JSONArray) {
        jsonset = (JSONArray) o;//from   w w w  .  ja  va2 s . c  o  m

    } else if (o instanceof JSONObject) {
        final JSONObject jso = (JSONObject) o;
        String java_class;

        // Hint presence
        try {
            java_class = jso.getString("javaClass");
        } catch (final JSONException e) {
            throw new UnmarshallException("Could not read javaClass", e);
        }
        if (java_class == null) {
            throw new UnmarshallException("no type hint");
        }

        // Class compatibility check
        if (!classNameCheck(java_class)) {
            throw new UnmarshallException("not a Set");
        }

        // JSON Format check
        try {
            jsonset = jso.getJSONArray("set");
        } catch (final JSONException e) {
            throw new UnmarshallException("set missing", e);
        }
    } else {
        throw new UnmarshallException("Given object is not JSON object/array");
    }

    if (jsonset == null) {
        throw new UnmarshallException("set missing");
    }

    // Content check
    final ObjectMatch m = new ObjectMatch(-1);
    state.setSerialized(o, m);

    int idx = 0;
    try {
        for (idx = 0; idx < jsonset.length(); idx++) {
            m.setMismatch(ser.tryUnmarshall(state, null, jsonset.get(idx)).max(m).getMismatch());
        }

    } catch (final UnmarshallException e) {
        throw new UnmarshallException("index " + idx + " " + e.getMessage(), e);
    } catch (final JSONException e) {
        throw new UnmarshallException("index " + idx + " " + e.getMessage(), e);
    }
    return m;
}