Example usage for org.json JSONArray length

List of usage examples for org.json JSONArray length

Introduction

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

Prototype

public int length() 

Source Link

Document

Get the number of elements in the JSONArray, included nulls.

Usage

From source file:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

private static void addRepeatToXml(Element root, Repeat repeat, JSONObject in, String section, String permlevel)
        throws JSONException, UnderlyingStorageException {
    if (repeat.isServicesReadOnly()) {
        // Omit fields that are read-only in the services layer.
        log.debug("Omitting services-readonly repeat: " + repeat.getID());
        return;/*  ww  w .  j  av  a 2  s  .c om*/
    }

    Element element = root;

    if (repeat.hasServicesParent()) {
        for (String path : repeat.getServicesParent()) {
            if (path != null) {
                element = element.addElement(path);
            }
        }
    } else if (!repeat.getXxxServicesNoRepeat()) { // Sometimes the UI is ahead of the services layer
        element = root.addElement(repeat.getServicesTag());
    }
    Object value = null;
    if (repeat.getXxxUiNoRepeat()) { // and sometimes the Servcies ahead of teh UI
        FieldSet[] children = repeat.getChildren(permlevel);
        if (children.length == 0)
            return;
        addFieldSetToXml(element, children[0], in, section, permlevel);
        return;
    } else {
        value = in.opt(repeat.getID());
    }

    if (value == null || ((value instanceof String) && StringUtils.isBlank((String) value)))
        return;
    if (value instanceof String) { // And sometimes the services ahead of the UI
        JSONArray next = new JSONArray();
        next.put(value);
        value = next;
    }
    if (!(value instanceof JSONArray))
        throw new UnderlyingStorageException(
                "Bad JSON in repeated field: must be string or array for repeatable field" + repeat.getID());
    JSONArray array = (JSONArray) value;

    //reorder the list if it has a primary
    //XXX this will be changed when service layer accepts non-initial values as primary
    if (repeat.hasPrimary()) {
        Stack<Object> orderedarray = new Stack<Object>();
        for (int i = 0; i < array.length(); i++) {
            Object one_value = array.get(i);
            if (one_value instanceof JSONObject) {
                if (((JSONObject) one_value).has("_primary")) {
                    if (((JSONObject) one_value).getBoolean("_primary")) {
                        orderedarray.add(0, one_value);
                        continue;
                    }
                }
            }
            orderedarray.add(one_value);
        }
        JSONArray newarray = new JSONArray();
        int j = 0;
        for (Object obj : orderedarray) {
            newarray.put(j, obj);
            j++;
        }
        array = newarray;
    }
    Element repeatelement = element;
    for (int i = 0; i < array.length(); i++) {
        if (repeat.hasServicesParent()) {
            repeatelement = element.addElement(repeat.getServicesTag());
        }
        Object one_value = array.get(i);
        if (one_value == null || ((one_value instanceof String) && StringUtils.isBlank((String) one_value)))
            continue;
        if (one_value instanceof String) {
            // Assume it's just the first entry (useful if there's only one)
            FieldSet[] fs = repeat.getChildren(permlevel);
            if (fs.length < 1)
                continue;
            JSONObject d1 = new JSONObject();
            d1.put(fs[0].getID(), one_value);
            addFieldSetToXml(repeatelement, fs[0], d1, section, permlevel);
        } else if (one_value instanceof JSONObject) {
            List<FieldSet> children = getChildrenWithGroupFields(repeat, permlevel);
            for (FieldSet fs : children)
                addFieldSetToXml(repeatelement, fs, (JSONObject) one_value, section, permlevel);
        }
    }
    element = repeatelement;
}

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;
                    }//from   w  ww .  j  a va2  s.c o  m
                    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:org.collectionspace.chain.csp.persistence.services.XmlJsonConversion.java

private static void addRepeatToJson(JSONObject out, Element root, Repeat f, String permlevel,
        JSONObject tempSon, String csid, String ims_url) throws JSONException {
    if (f.getXxxServicesNoRepeat()) { //not a repeat in services yet but is a repeat in UI
        FieldSet[] fields = f.getChildren(permlevel);
        if (fields.length == 0)
            return;
        JSONArray members = new JSONArray();
        JSONObject data = new JSONObject();
        addFieldSetToJson(data, root, fields[0], permlevel, tempSon, csid, ims_url);
        members.put(data);/*from w w  w  .  j a  v  a  2  s . c o m*/
        out.put(f.getID(), members);
        return;
    }
    String nodeName = f.getServicesTag();
    if (f.hasServicesParent()) {
        nodeName = f.getfullID();
        //XXX hack because of weird repeats in accountroles permroles etc
        if (f.getServicesParent().length == 0) {
            nodeName = f.getID();
        }
    }
    List<?> nodes = root.selectNodes(nodeName);
    if (nodes.size() == 0) {// add in empty primary tags and arrays etc to help UI
        if (f.asSibling()) {
            JSONObject repeated = new JSONObject();
            if (f.hasPrimary()) {
                repeated.put("_primary", true);
            }
            if (!out.has(f.getID())) {
                JSONArray temp = new JSONArray();
                out.put(f.getID(), temp);
            }
            out.getJSONArray(f.getID()).put(repeated);
        } else {
            JSONArray repeatitem = new JSONArray();
            out.put(f.getID(), repeatitem);
        }
        return;
    }

    // Only first element is important in container
    //except when we have repeating items
    int pos = 0;
    for (Object repeatcontainer : nodes) {
        pos++;
        Element container = (Element) repeatcontainer;
        if (f.asSibling()) {
            JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon);
            JSONArray temp = new JSONArray();
            if (!out.has(f.getID())) {
                out.put(f.getID(), temp);
            }
            for (int arraysize = 0; arraysize < repeatitem.length(); arraysize++) {
                JSONObject repeated = repeatitem.getJSONObject(arraysize);

                if (f.hasPrimary() && pos == 1) {
                    repeated.put("_primary", true);
                }
                out.getJSONArray(f.getID()).put(repeated);
            }
        } else {
            JSONArray repeatitem = addRepeatedNodeToJson(container, f, permlevel, tempSon);
            out.put(f.getID(), repeatitem);
        }
    }
}

From source file:nl.hnogames.domoticzapi.Parsers.DevicesParser.java

@Override
public void parseResult(String result) {

    try {/* ww  w .  j  a  v a  2 s  .  c o  m*/
        JSONArray jsonArray = new JSONArray(result);
        ArrayList<DevicesInfo> mDevices = new ArrayList<>();

        if (jsonArray.length() > 0) {

            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject row = jsonArray.getJSONObject(i);
                mDevices.add(new DevicesInfo(row));
            }
        }

        if (idx == 999999)
            receiver.onReceiveDevices(mDevices);
        else {
            receiver.onReceiveDevice(getDevice(idx, mDevices, scene_or_group));
        }
    } catch (JSONException e) {
        Log.e(TAG, "DevicesParser JSON exception");
        e.printStackTrace();
        receiver.onError(e);
    }
}

From source file:org.catnut.fragment.FavoriteFragment.java

@Override
protected void refresh() {
    // ???//from  w w  w  . jav  a  2  s.  c o m
    if (!isNetworkAvailable()) {
        Toast.makeText(getActivity(), getString(R.string.network_unavailable), Toast.LENGTH_SHORT).show();
        initFromLocal();
        return;
    }
    // ??
    mCurrentPage = 0;
    mDeleteCount = 0;
    mTotal = 0;

    // go go go
    mRequestQueue.add(new CatnutRequest(getActivity(), FavoritesAPI.favorites(getFetchSize(), mCurrentPage),
            new StatusProcessor.FavoriteTweetsProcessor(), new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    Log.d(TAG, "refresh done...");
                    mDeleteCount += response.optInt(TAG);
                    mTotal = response.optInt(TOTAL_NUMBER);
                    // ???
                    JSONArray jsonArray = response.optJSONArray(Status.FAVORITES);
                    int newSize = jsonArray.length(); // ...
                    Bundle args = new Bundle();
                    args.putInt(TAG, newSize);
                    getLoaderManager().restartLoader(0, args, FavoriteFragment.this);
                }
            }, errorListener)).setTag(TAG);
}

From source file:com.phonegap.Storage.java

/**
 * Executes the request and returns PluginResult.
 * // w w  w . ja v  a2s . c o  m
 * @param action       The action to execute.
 * @param args          JSONArry of arguments for the plugin.
 * @param callbackId   The callback id used when calling back into JavaScript.
 * @return             A PluginResult object with a status and message.
 */
public PluginResult execute(String action, JSONArray args, String callbackId) {
    PluginResult.Status status = PluginResult.Status.OK;
    String result = "";

    try {
        // TODO: Do we want to allow a user to do this, since they could get to other app databases?
        if (action.equals("setStorage")) {
            this.setStorage(args.getString(0));
        } else if (action.equals("openDatabase")) {
            this.openDatabase(args.getString(0), args.getString(1), args.getString(2), args.getLong(3));
        } else if (action.equals("executeSql")) {
            JSONArray a = args.getJSONArray(1);
            int len = a.length();
            String[] s = new String[len];
            for (int i = 0; i < len; i++) {
                s[i] = a.getString(i);
            }
            this.executeSql(args.getString(0), s, args.getString(2));
        }
        return new PluginResult(status, result);
    } catch (JSONException e) {
        return new PluginResult(PluginResult.Status.JSON_EXCEPTION);
    }
}

From source file:com.rsimiao.exemplosloopj.UsuarioWS.java

public void buscar(final Handler handler) {

    try {/*ww  w .j  a v a  2 s  . c o  m*/
        RequestParams parametros = new RequestParams();
        parametros.add("limite", "todos");

        Wscliente.post(url, parametros, new AsyncHttpResponseHandler() {
            @Override
            public void onFailure(int code, Header[] header, byte[] conteudo, Throwable arg3) {
                //voc pode colocar aqui seu tratamento de erro
                Log.d("WS USUARIO", "DEU ERRO");
                Message msg = new Message();
                msg.what = 0; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro.
                handler.sendMessage(msg);
            }

            @Override
            public void onSuccess(int code, Header[] header, byte[] conteudo) {
                try {
                    JSONObject json = new JSONObject(new String(conteudo));
                    List<Usuario> usuarios = new ArrayList<Usuario>();
                    //sua lgica para tratar o json recebido (no precisa ser desse modo jurstico)
                    if (json.has("status") && json.getString("status").equalsIgnoreCase("success")) {

                        JSONArray jUsrs = json.getJSONArray("usuarios");

                        for (int i = 0; i < jUsrs.length(); i++) {
                            Usuario u = new Usuario();
                            u.setNome(jUsrs.getJSONObject(i).getString("nome"));
                            u.setUsuario(jUsrs.getJSONObject(i).getString("usuario"));
                            u.setLogged(jUsrs.getJSONObject(i).getBoolean("islogged"));
                            usuarios.add(u);
                        }

                        Message msg = new Message();
                        msg.what = 1; //defino um identificador para a msg coloco 1 para sucesso e 0 para erro.
                        msg.obj = usuarios;
                        handler.sendMessage(msg);

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

        });

    } catch (Exception e) {
        e.printStackTrace();
    }

}

From source file:com.google.android.apps.paco.ExperimentExecutorCustomRendering.java

private static String convertEventsToJsonString(final Experiment experiment, List<Event> events) {
    // TODO use jackson instead. But preserve these synthesized values for backward compatibility.
    final JSONArray experimentData = new JSONArray();
    for (Event event : events) {
        try {//ww  w.j a v a  2 s .c  o  m
            JSONObject eventObject = new JSONObject();
            boolean missed = event.getResponseTime() == null;
            eventObject.put("isMissedSignal", missed);
            if (!missed) {
                eventObject.put("responseTime", event.getResponseTime().getMillis());
            }

            boolean selfReport = event.getScheduledTime() == null;
            eventObject.put("isSelfReport", selfReport);
            if (!selfReport) {
                eventObject.put("scheduleTime", event.getScheduledTime().getMillis());
            }

            JSONArray responses = new JSONArray();
            for (Output response : event.getResponses()) {
                JSONObject responseJson = new JSONObject();
                Input input = experiment.getInputById(response.getInputServerId());
                if (input == null) {
                    continue;
                }
                responseJson.put("inputId", input.getServerId());
                // deprecate inputName in favor of name
                responseJson.put("inputName", input.getName());
                responseJson.put("name", input.getName());
                responseJson.put("responseType", input.getResponseType());
                responseJson.put("isMultiselect", input.isMultiselect());
                responseJson.put("prompt", getTextOfInputForOutput(experiment, response));
                responseJson.put("answer", response.getDisplayOfAnswer(input));
                // deprecated for answerRaw
                responseJson.put("answerOrder", response.getAnswer());
                responseJson.put("answerRaw", response.getAnswer());
                responses.put(responseJson);
            }

            eventObject.put("responses", responses);
            if (responses.length() > 0) {
                experimentData.put(eventObject);
            }
        } catch (JSONException jse) {
            // skip this event and do the next event.
        }
    }
    String experimentDataAsJson = experimentData.toString();
    return experimentDataAsJson;
}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Gets the last completed thermostat job.
 * /*from  w w  w .j a  v a2 s.  co m*/
 * @param thermostatId
 *            the thermostat id
 * @return the last completed thermostat job
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#getLastCompletedThermostatJob(java.lang.Integer)
 */
@Override
public ThermostatJob getLastCompletedThermostatJob(Integer thermostatId) {

    ThermostatJob thermostatJob = null;
    JSONArray jsonArray = getJobData(thermostatId);
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            thermostatJob = new ThermostatJob();
            Calendar calendar = DateUtil.getUTCCalendar();
            JSONObject jsonObj = jsonArray.getJSONObject(i);

            thermostatJob.setThermostatId(thermostatId);
            thermostatJob.setJobData(jsonObj.toString());

            thermostatJob.setStartDate(calendar);
            thermostatJob.setEndDate(calendar);

            thermostatJob.setJobType("SPO");
            thermostatJob.setAlgorithmId(190);
            thermostatJob.setJobStatus(ThermostatJob.Status.PROCESSED);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return thermostatJob;
}

From source file:com.ecofactor.qa.automation.newapp.service.MockDataServiceImpl.java

/**
 * Checks if is sPO block active./*from w w w.j  a  v  a  2  s . c o m*/
 * 
 * @param thermostatId
 *            the thermostat id
 * @param algoId
 *            the algo id
 * @return true, if is sPO block active
 * @see com.ecofactor.qa.automation.algorithm.service.DataService#isSPOBlockActive(java.lang.Integer,
 *      int)
 */
@Override
public boolean isSPOBlockActive(Integer thermostatId, int algoId) {

    log("Check if SPO is active for thermostat :" + thermostatId, true);
    boolean spoActive = false;
    Thermostat thermostat = findBythermostatId(thermostatId);
    Calendar currentTime = (Calendar) Calendar.getInstance(TimeZone.getTimeZone(thermostat.getTimezone()))
            .clone();

    JSONArray jsonArray = getJobData(thermostatId);
    for (int i = 0; i < jsonArray.length(); i++) {
        try {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            Calendar startCal = DateUtil.getTimeZoneCalendar((String) jsonObj.get("start"),
                    thermostat.getTimezone());
            Calendar endcal = DateUtil.getTimeZoneCalendar((String) jsonObj.get("end"),
                    thermostat.getTimezone());

            if (currentTime.after(startCal) && currentTime.before(endcal)) {
                spoActive = true;
                break;
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return spoActive;
}