Example usage for org.json JSONObject optJSONArray

List of usage examples for org.json JSONObject optJSONArray

Introduction

In this page you can find the example usage for org.json JSONObject optJSONArray.

Prototype

public JSONArray optJSONArray(String key) 

Source Link

Document

Get an optional JSONArray associated with a key.

Usage

From source file:com.galactogolf.serialization.JSONSerializer.java

private static LevelDefinition fromLevelDefinitionJSON(JSONObject levelDefnJSON) throws JSONException {
    LevelDefinition levelDefn = new LevelDefinition(levelDefnJSON.getString(JSONTags.LEVEL_DEFINITION_NAME));
    levelDefn.setDescription(levelDefnJSON.optString(JSONTags.LEVEL_DEFINITION_DESCRIPTION));
    levelDefn.setPar(levelDefnJSON.optInt(JSONTags.LEVEL_DEFINITION_PAR));

    JSONArray npcsJSON = levelDefnJSON.optJSONArray(JSONTags.LEVEL_DEFINITION_NPCS);
    if (npcsJSON != null) {
        for (int i = 0; i < npcsJSON.length(); i++) {
            levelDefn.GetNPCDefinitions()
                    .add(JSONSerializer.fromEntityDefinitionJSON(npcsJSON.getJSONObject(i)));
        }//from   w  w  w.  j a  v a 2 s .  c  o  m
    }
    levelDefn.setPlayerDefinition(JSONSerializer
            .fromEntityDefinitionJSON(levelDefnJSON.getJSONObject(JSONTags.LEVEL_DEFINITION_PLAYER)));

    return levelDefn;

}

From source file:com.rapid.actions.Mobile.java

public Mobile(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    this();//from  w w  w.j  av a 2  s.c o m
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for success and error actions
        if (!"successActions".equals(key) && !"errorActions".equals(key) && !"onlineActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // upload images was modified to have a number of gallery ids (rather than 1) migrate for old versions
    String type = getProperty("actionType");
    // if this is upload images
    if ("uploadImages".equals(type)) {
        // get any single gallery controlId
        String galleryControlId = getProperty("galleryControlId");
        // if not null
        if (galleryControlId != null) {
            // empty the property
            _properties.remove("galleryControlId");
            // move it into the galleryControlIds
            _properties.put("galleryControlIds", "[\"" + galleryControlId + "\"]");
        }
    }

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some
    if (jsonSuccessActions != null) {
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);
    }

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some
    if (jsonErrorActions != null) {
        // instantiate our contols collection
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);
    }

    // grab any onlineActions
    JSONArray jsonOnlineActions = jsonAction.optJSONArray("onlineActions");
    // if we had some
    if (jsonOnlineActions != null) {
        // instantiate our contols collection
        _onlineActions = Control.getActions(rapidServlet, jsonOnlineActions);
    }
}

From source file:ded.model.Relation.java

public Relation(JSONObject o, ArrayList<Entity> integerToEntity, ArrayList<Inheritance> integerToInheritance,
        int version) throws JSONException {
    this.start = new RelationEndpoint(o.getJSONObject("start"), integerToEntity, integerToInheritance,
            ArrowStyle.AS_NONE, version);
    this.end = new RelationEndpoint(o.getJSONObject("end"), integerToEntity, integerToInheritance,
            ArrowStyle.AS_FILLED_TRIANGLE, version);

    JSONArray pts = o.optJSONArray("controlPts");
    if (pts != null) {
        for (int i = 0; i < pts.length(); i++) {
            this.controlPts.add(AWTJSONUtil.pointFromJSON(pts.getJSONObject(i)));
        }/*from  w ww .  j  av  a 2s .  c  om*/
    }

    if (o.has("routingAlg")) {
        this.routingAlg = RoutingAlgorithm.valueOf(RoutingAlgorithm.class, o.getString("routingAlg"));
    }

    this.label = o.optString("label", "");

    if (version < 9) {
        // The end arrowhead style was associated with the relation itself.
        this.setLegacyOwning(o.optBoolean("owning", false));
    }

    if (o.has("lineWidth")) {
        this.lineWidth = Integer.valueOf(o.getInt("lineWidth"));
    }
}

From source file:com.rapid.actions.Datacopy.java

public Datacopy(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();/* w w w . j a  v a2 s .c o  m*/
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for dataCopies
        if (!"dataCopies".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }
    // look for a dataCopies array
    JSONArray jsonDataCopies = jsonAction.optJSONArray("dataCopies");
    // if we got one
    if (jsonDataCopies != null) {
        // instantiate our collection
        _dataCopies = new ArrayList<DataCopy>();
        // loop it
        for (int i = 0; i < jsonDataCopies.length(); i++) {
            // add this one
            _dataCopies.add(new DataCopy(jsonDataCopies.getJSONObject(i)));
        }
    }
}

From source file:ded.model.Entity.java

public Entity(JSONObject o, int ver) throws JSONException {
    this.loc = AWTJSONUtil.pointFromJSON(o.getJSONObject("loc"));
    this.size = AWTJSONUtil.dimensionFromJSON(o.getJSONObject("size"));

    if (o.has("shape")) {
        this.shape = EntityShape.valueOf(EntityShape.class, o.getString("shape"));
    }/*from w  w w . j a v  a  2  s  . c  om*/

    this.name = o.optString("name", "");
    this.attributes = o.optString("attributes", "");

    JSONArray params = o.optJSONArray("shapeParams");
    if (params != null) {
        this.shapeParams = new int[params.length()];
        for (int i = 0; i < params.length(); i++) {
            this.shapeParams[i] = params.getInt(i);
        }
    }

    JSONArray flags = o.optJSONArray("shapeFlags");
    if (flags != null) {
        this.shapeFlags = AWTJSONUtil.enumSetFromJSON(ShapeFlag.class, flags);
    }

    if (ver >= 5) {
        this.fillColor = o.optString("fillColor", defaultFillColor);
    }

    if (ver >= 12) {
        this.anchorName = o.optString("anchorName", "");
    }

    if (ver >= 7) {
        this.imageFileName = o.optString("imageFileName", "");
    }

    if (ver >= 8 && o.has("imageFillStyle")) {
        this.imageFillStyle = ImageFillStyle.valueOf(ImageFillStyle.class, o.getString("imageFillStyle"));
    }
}

From source file:com.facebook.stream.StreamRenderer.java

/**
 * Returns the available actions for the post.
 * //from   w w w.j  a v a  2  s .co  m
 * @param post
 * @return
 */
private HashSet<String> getActions(JSONObject post) {
    HashSet<String> actionsSet = new HashSet<String>();
    JSONArray actions = post.optJSONArray("actions");
    if (actions != null) {
        for (int j = 0; j < actions.length(); j++) {
            JSONObject action = actions.optJSONObject(j);
            String actionName = action.optString("name");
            actionsSet.add(actionName);
        }
    }
    return actionsSet;
}

From source file:com.facebook.stream.StreamRenderer.java

/**
 * Renders the post's comments./* www  .  ja v  a  2  s  .  com*/
 * 
 * @param post
 * @throws JSONException
 */
private void renderComments(JSONObject post) throws JSONException {
    append("<div class=\"comments\" id=\"comments" + post.optString("id") + "\">");
    JSONObject comments = post.optJSONObject("comments");
    if (comments != null) {
        JSONArray data = comments.optJSONArray("data");
        if (data != null) {
            for (int j = 0; j < data.length(); j++) {
                JSONObject comment = data.getJSONObject(j);
                renderComment(comment);
            }
        }
    }
    append("</div>");
}

From source file:com.dbmojo.QueryExecutor.java

/**
 * Execute a set of queries/updates encoded in JSON via <b>reqStr</b> in the 
 * format <br><br><i>[{query:"select x from y",values:[]},{}&#46;&#46;&#46;]
 * </i>&#46;<br><br>The <b>update</b> flag determines whether or not to 
 * treat each statement in the <b>reqStr</b> as an update or a query&#46;
 *///from  ww w  . j  a  v  a2 s. c o  m
public String execute(String reqStr, boolean update) throws Exception {

    if (DebugLog.enabled) {
        DebugLog.add(this, "Begin execute");
    }

    String message = "";
    ArrayList<HashMap> resultsList = new ArrayList<HashMap>();
    LinkedHashMap<String, PreparedStatement> bpstmts = null;
    Statement bstmt = null;

    try {
        this.open(update);

        if (update) {
            conn.setAutoCommit(false);
        }

        final JSONArray reqs = new JSONArray(reqStr);
        final boolean batchUpdates = reqs.length() > 1;

        //Connection MUST be ready to go
        if (this.conn == null) {
            throw new QueryExecutorException("Connection could not be checked out");
        }

        final int rLen = reqs.length();

        if (rLen <= 0) {
            throw new QueryExecutorException("No queries specified");
        }

        for (int r = 0; r < rLen; r++) {
            String rMessage = "";
            final JSONObject reqObj = reqs.getJSONObject(r);
            JSONArray tValues = reqObj.optJSONArray("values");
            String[] values = new String[(tValues != null ? tValues.length() : 0)];

            //Convert the JSONArray to a String[]
            for (int v = 0; v < values.length; v++) {
                values[v] = tValues.getString(v);
            }

            String query = reqObj.getString("query");
            final boolean prepared = values != null;

            //Can't move forward without a query!
            if (query == null || query.equals("")) {
                throw new QueryExecutorException("Query is missing");
            }

            //Here's where we need to do either an update or a query
            if (update) {
                if (batchUpdates) {
                    // This is NOT a prepared statement and we need to create a
                    // batch statement to add all non prepared statements to
                    if (!prepared && bstmt == null) {
                        bstmt = conn.createStatement();

                        // This IS a prepared statement and we need to create a
                        // ordered map of prepared statements so we can execute
                        // these statements together in order (sortof...)
                    } else if (prepared && bpstmts == null) {
                        bpstmts = new LinkedHashMap<String, PreparedStatement>();
                    }

                    addBatchUpdate(this.conn, prepared, query, values, bstmt, bpstmts);
                } else {

                    // Single update query / prepared statement to execute
                    executeUpdate(this.conn, prepared, query, values);
                }
            } else {
                resultsList.add(executeQuery(this.conn, prepared, query, values));
            }
        }

        //Execute Batch Updates
        if (update && batchUpdates) {
            //Execute any prepared statement batches that have been gathered.
            //If we have an SQL error and exception will be thrown
            if (bpstmts != null && bpstmts.size() > 0) {
                for (PreparedStatement p : bpstmts.values()) {
                    if (DebugLog.enabled) {
                        DebugLog.add(this, "Executing batch prepared statement");
                    }

                    p.executeBatch();
                }
            }

            //Execute all the standard SQL in a batch. 
            //If we have a SQL error an Exception will be thrown
            if (bstmt != null) {
                if (DebugLog.enabled) {
                    DebugLog.add(this, "Executing batch statement");
                }

                bstmt.executeBatch();
            }
        }

        if (update) {
            this.conn.commit();
        }

    } catch (JSONException je) {

        //There was an error parsing the JSON
        final String err = je.toString();
        if (DebugLog.enabled) {
            DebugLog.add(this, err);
        }

        resultsList.add(Util.getError(err));

    } catch (Exception e) {

        //We couldn't connect to the DB...      
        if (this.conn == null) {
            final String err = e.toString();

            if (ErrorLog.enabled) {
                ErrorLog.add(this, err, false);
            }

            resultsList.add(Util.getError(err));

            //There was an error executing the query/update
        } else if (update) {
            final String err = "Rolling Back Update(s): " + e;

            if (DebugLog.enabled) {
                DebugLog.add(this, err);
            }

            if (this.conn != null) {
                this.conn.rollback();
            }

            resultsList.add(Util.getError(err));
        } else {
            final String err = e.toString();

            if (DebugLog.enabled) {
                DebugLog.add(this, err);
            }

            resultsList.add(Util.getError(err));
        }

    } finally {
        //Cleanup batch statement (If applicable)
        if (bstmt != null) {
            try {
                if (DebugLog.enabled) {
                    DebugLog.add(this, "Closing batch statement");
                }
                bstmt.close();
            } catch (Exception se) {
                String err = "Error closing batch statement - " + se.toString();
                if (ErrorLog.enabled) {
                    ErrorLog.add(this, err, false);
                }
                resultsList.add(Util.getError(err));
            }
        }

        //Cleanup the batch prepared statement (If applicable)
        if (bpstmts != null) {
            for (PreparedStatement p : bpstmts.values()) {
                try {
                    if (p != null) {
                        p.close();
                        if (DebugLog.enabled) {
                            DebugLog.add(this, "Closing batch prepared stmnt");
                        }
                    }
                } catch (Exception pse) {
                    String err = "Error closing batch prepared stmnt - " + pse.toString();
                    if (ErrorLog.enabled) {
                        ErrorLog.add(this, err, false);
                    }
                    resultsList.add(Util.getError(err));
                }
            }
        }

        if (DebugLog.enabled) {
            DebugLog.add(this, "Closing connection");
        }

        //Cleanup DB connection (Always applicable)
        this.conn.close();
    }

    if (DebugLog.enabled) {
        DebugLog.add(this, "End execute");
    }

    //UPDATE => [{message:"",status:"success"}]
    if (update && resultsList.size() <= 0) {

        HashMap pObj = new HashMap();
        pObj.put("message", "");
        pObj.put("status", "success");
        pObj.put("rows", new ArrayList());
        pObj.put("types", new ArrayList());
        pObj.put("cols", new ArrayList());
        resultsList.add(pObj);

    }

    //Serialize resultsArray into JSON
    return serializeToJson(resultsList);
}

From source file:com.zotoh.core.util.JSONUte.java

/**
 * @param obj//from   w  ww  .j av  a 2 s.c  om
 * @param key
 * @return
 */
public static JSONArray getArray(JSONObject obj, String key) {
    return obj == null ? null : obj.optJSONArray(key);
}

From source file:com.rapid.actions.Database.java

public Database(RapidHttpServlet rapidServlet, JSONObject jsonAction) throws Exception {
    // call the super parameterless constructor which sets the xml version
    super();/*from  ww w  . j  a  va2 s . com*/
    // save all key/values from the json into the properties 
    for (String key : JSONObject.getNames(jsonAction)) {
        // add all json properties to our properties, except for query
        if (!"query".equals(key) && !"showLoading".equals(key) && !"childDatabaseActions".equals(key)
                && !"successActions".equals(key) && !"errorActions".equals(key) && !"childActions".equals(key))
            addProperty(key, jsonAction.get(key).toString());
    }

    // try and build the query object
    JSONObject jsonQuery = jsonAction.optJSONObject("query");

    // check we got one
    if (jsonQuery != null) {
        // get the parameters                  
        ArrayList<Parameter> inputs = getParameters(jsonQuery.optJSONArray("inputs"));
        ArrayList<Parameter> outputs = getParameters(jsonQuery.optJSONArray("outputs"));
        String sql = jsonQuery.optString("SQL");
        boolean multiRow = jsonQuery.optBoolean("multiRow");
        int databaseConnectionIndex = jsonQuery.optInt("databaseConnectionIndex");
        // make the object
        _query = new Query(inputs, outputs, sql, multiRow, databaseConnectionIndex);
    }

    // look for showLoading
    _showLoading = jsonAction.optBoolean("showLoading");

    // grab any successActions
    JSONArray jsonChildDatabaseActions = jsonAction.optJSONArray("childDatabaseActions");
    // if we had some 
    if (jsonChildDatabaseActions != null) {
        // instantiate collection
        _childDatabaseActions = new ArrayList<Database>();
        // loop them
        for (int i = 0; i < jsonChildDatabaseActions.length(); i++) {
            // get one
            JSONObject jsonChildDatabaseAction = jsonChildDatabaseActions.getJSONObject(i);
            // instantiate and add to collection
            _childDatabaseActions.add(new Database(rapidServlet, jsonChildDatabaseAction));
        }
    }

    // grab any successActions
    JSONArray jsonSuccessActions = jsonAction.optJSONArray("successActions");
    // if we had some instantiate our collection
    if (jsonSuccessActions != null)
        _successActions = Control.getActions(rapidServlet, jsonSuccessActions);

    // grab any errorActions
    JSONArray jsonErrorActions = jsonAction.optJSONArray("errorActions");
    // if we had some instantiate our collection
    if (jsonErrorActions != null)
        _errorActions = Control.getActions(rapidServlet, jsonErrorActions);

}