Example usage for org.json JSONArray JSONArray

List of usage examples for org.json JSONArray JSONArray

Introduction

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

Prototype

public JSONArray() 

Source Link

Document

Construct an empty JSONArray.

Usage

From source file:fr.arnaudguyon.xmltojsonlib.XmlToJson.java

private JSONObject convertTagToJson(Tag tag, boolean isListElement) {
    JSONObject json = new JSONObject();

    // Content is injected as a key/value
    if (tag.getContent() != null) {
        String path = tag.getPath();
        String name = getContentNameReplacement(path, DEFAULT_CONTENT_NAME);
        putContent(path, json, name, tag.getContent());
    }/*from w w w  . ja  va  2  s  . co  m*/

    try {

        HashMap<String, ArrayList<Tag>> groups = tag.getGroupedElements(); // groups by tag names so that we can detect lists or single elements
        for (ArrayList<Tag> group : groups.values()) {

            if (group.size() == 1) { // element, or list of 1
                Tag child = group.get(0);
                if (isForcedList(child)) { // list of 1
                    JSONArray list = new JSONArray();
                    list.put(convertTagToJson(child, true));
                    String childrenNames = child.getName();
                    json.put(childrenNames, list);
                } else { // stand alone element
                    if (child.hasChildren()) {
                        JSONObject jsonChild = convertTagToJson(child, false);
                        json.put(child.getName(), jsonChild);
                    } else {
                        String path = child.getPath();
                        putContent(path, json, child.getName(), child.getContent());
                    }
                }
            } else { // list
                JSONArray list = new JSONArray();
                for (Tag child : group) {
                    list.put(convertTagToJson(child, true));
                }
                String childrenNames = group.get(0).getName();
                json.put(childrenNames, list);
            }
        }
        return json;

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

From source file:com.maxleapmobile.gitmaster.ui.fragment.RecommendFragment.java

private void getGenes() {
    MLQueryManager.findAllInBackground(query, new FindCallback<MLObject>() {
        @Override//from   ww w  .  j  a v  a2  s.  com
        public void done(List<MLObject> list, MLException e) {
            if (e == null) {
                Logger.d("get genes success");
                for (MLObject o : list) {
                    genes.add(Gene.from(o));
                }
                JSONArray jsonArray = new JSONArray();
                for (int i = 0; i < genes.size(); i++) {
                    JSONObject jsonObject = new JSONObject();
                    try {
                        jsonObject.put("language", genes.get(i).getLanguage());
                        jsonObject.put("skill", genes.get(i).getSkill());
                        jsonArray.put(i, jsonObject);
                    } catch (Exception jsonException) {

                    }
                }
                mParmasMap.put("genes", jsonArray);
                fetchTrendingGeneDate();
            } else {
                Logger.d("get genes failed");
                if (e.getCode() == MLException.OBJECT_NOT_FOUND) {
                    fetchSearchGeneDate();
                } else {
                    Logger.toast(mContext, R.string.toast_get_recommend_failed);
                }
            }
        }
    });
}

From source file:com.maxleapmobile.gitmaster.ui.fragment.RecommendFragment.java

private void compareGenes() {
    Logger.d("compareGenes start");
    MLQueryManager.findAllInBackground(query, new FindCallback<MLObject>() {
        @Override//from ww w.j a va2s.  c o m
        public void done(List<MLObject> list, MLException e) {
            if (e == null) {
                Logger.d("compareGenes success");
                boolean needRefresh = false;
                ArrayList<Gene> newGenes = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    Gene gene = Gene.from(list.get(i));
                    if (!needRefresh && !genes.contains(gene)) {
                        genes.add(gene);
                        needRefresh = true;
                    }
                    newGenes.add(gene);
                }
                if (needRefresh) {
                    genes = newGenes;
                    JSONArray jsonArray = new JSONArray();
                    for (int i = 0; i < genes.size(); i++) {
                        JSONObject jsonObject = new JSONObject();
                        try {
                            jsonObject.put("language", genes.get(i).getLanguage());
                            jsonObject.put("skill", genes.get(i).getSkill());
                            jsonArray.put(i, jsonObject);
                        } catch (Exception jsonException) {

                        }
                    }
                    mParmasMap.put("genes", jsonArray);
                    isEnd = false;
                    isReview = false;
                    repos.clear();
                    fetchTrendingGeneDate();
                } else {
                    loadUrl();
                    mProgressBar.setVisibility(View.GONE);
                    mEmptyView.setVisibility(View.GONE);
                    actionArea.setEnabled(true);
                }
            } else {
                loadUrl();
                Logger.d("compareGenes failed");
                mProgressBar.setVisibility(View.GONE);
            }
        }
    });
}

From source file:org.bcsphere.bluetooth.BCBluetooth.java

@Override
public boolean execute(final String action, final JSONArray json, final CallbackContext callbackContext)
        throws JSONException {
    try {//from w  w  w .  j  a v a 2  s . c  o m
        if (bluetoothAPI != null) {
            if (isSetContext) {
                bluetoothAPI.setContext(myContext);
                isSetContext = false;
            }
            if (action.equals("getCharacteristics")) {
                bluetoothAPI.getCharacteristics(json, callbackContext);
            } else if (action.equals("getDescriptors")) {
                bluetoothAPI.getDescriptors(json, callbackContext);
            } else if (action.equals("removeServices")) {
                bluetoothAPI.removeServices(json, callbackContext);
            }
            if (action.equals("stopScan")) {
                bluetoothAPI.stopScan(json, callbackContext);
            } else if (action.equals("getConnectedDevices")) {
                bluetoothAPI.getConnectedDevices(json, callbackContext);
            }

            cordova.getThreadPool().execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (action.equals("startScan")) {
                            bluetoothAPI.startScan(json, callbackContext);
                        } else if (action.equals("connect")) {
                            bluetoothAPI.connect(json, callbackContext);
                        } else if (action.equals("disconnect")) {
                            bluetoothAPI.disconnect(json, callbackContext);
                        } else if (action.equals("getServices")) {
                            bluetoothAPI.getServices(json, callbackContext);
                        } else if (action.equals("writeValue")) {
                            bluetoothAPI.writeValue(json, callbackContext);
                        } else if (action.equals("readValue")) {
                            bluetoothAPI.readValue(json, callbackContext);
                        } else if (action.equals("setNotification")) {
                            bluetoothAPI.setNotification(json, callbackContext);
                        } else if (action.equals("getDeviceAllData")) {
                            bluetoothAPI.getDeviceAllData(json, callbackContext);
                        } else if (action.equals("addServices")) {
                            bluetoothAPI.addServices(json, callbackContext);
                        } else if (action.equals("getRSSI")) {
                            bluetoothAPI.getRSSI(json, callbackContext);
                        }
                    } catch (Exception e) {
                        Tools.sendErrorMsg(callbackContext);
                    } catch (Error e) {
                        Tools.sendErrorMsg(callbackContext);
                    }
                }
            });
        }

        if (action.equals("addEventListener")) {
            String eventName = Tools.getData(json, Tools.EVENT_NAME);
            if (eventName.equals("newadvpacket")) {
                newadvpacketContext = callbackContext;
            } else if (eventName.equals("disconnect")) {
                disconnectContext = callbackContext;
            }
            if (bluetoothAPI != null) {
                bluetoothAPI.addEventListener(json, callbackContext);
            }
            return true;
        }

        if (action.equals("getEnvironment")) {
            JSONObject jo = new JSONObject();
            if (this.webView.page != null) {
                jo.put("deviceAddress", this.webView.page.deviceAddress);
                jo.put("deviceType", this.webView.page.deviceType);
                jo.put("api", versionOfAPI);
            } else {
                jo.put("deviceAddress", "N/A");
                jo.put("deviceType", "N/A");
                jo.put("api", versionOfAPI);
            }
            callbackContext.success(jo);
            return true;
        }
        if (action.equals("openBluetooth")) {
            if (!bluetoothAdapter.isEnabled()) {
                bluetoothAdapter.enable();
            }
            Tools.sendSuccessMsg(callbackContext);
            return true;
        }
        if (action.equals("getBluetoothState")) {
            Log.i(TAG, "getBluetoothState");
            JSONObject obj = new JSONObject();
            if (bluetoothAdapter.isEnabled()) {
                Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_TRUE);
                callbackContext.success(obj);
            } else {
                Tools.addProperty(obj, Tools.BLUETOOTH_STATE, Tools.IS_FALSE);
                callbackContext.success(obj);
            }
            return true;
        }
        if (action.equals("startClassicalScan")) {
            Log.i(TAG, "startClassicalScan");
            if (bluetoothAdapter.isEnabled()) {
                if (bluetoothAdapter.startDiscovery()) {
                    callbackContext.success();
                } else {
                    callbackContext.error("start classical scan error!");
                }
            } else {
                callbackContext.error("your bluetooth is not open!");
            }
        }
        if (action.equals("stopClassicalScan")) {
            Log.i(TAG, "stopClassicalScan");
            if (bluetoothAdapter.isEnabled()) {
                if (bluetoothAdapter.cancelDiscovery()) {
                    callbackContext.success();
                } else {
                    callbackContext.error("stop classical scan error!");
                }
            } else {
                callbackContext.error("your bluetooth is not open!");
            }
        }
        if (action.equals("rfcommConnect")) {
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            String securestr = Tools.getData(json, Tools.SECURE);
            String uuidstr = Tools.getData(json, Tools.UUID);
            boolean secure = false;
            if (securestr != null && securestr.equals("true")) {
                secure = true;
            }
            Log.i(TAG, "connect to " + deviceAddress);
            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
            BluetoothSerialService classicalService = classicalServices.get(deviceAddress);

            if (device != null && classicalService == null) {
                classicalService = new BluetoothSerialService();
                classicalService.disconnectCallback = disconnectContext;
                classicalServices.put(deviceAddress, classicalService);
            }

            if (device != null) {
                classicalService.connectCallback = callbackContext;
                classicalService.connect(device, uuidstr, secure);
            } else {
                callbackContext.error("Could not connect to " + deviceAddress);
            }
        }
        if (action.equals("rfcommDisconnect")) {
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            BluetoothSerialService service = classicalServices.get(deviceAddress);
            if (service != null) {
                service.connectCallback = null;
                service.stop();
                classicalServices.remove(deviceAddress);
                callbackContext.success();
            } else {
                callbackContext.error("Could not disconnect to " + deviceAddress);
            }
        }
        if (action.equals("rfcommListen")) {
            String name = Tools.getData(json, Tools.NAME);
            String uuidstr = Tools.getData(json, Tools.UUID);
            String securestr = Tools.getData(json, Tools.SECURE);
            boolean secure = false;
            if (securestr.equals("true")) {
                secure = true;
            }
            BluetoothSerialService service = new BluetoothSerialService();
            service.listen(name, uuidstr, secure, this);
            acceptServices.put(name + uuidstr, service);
        }
        if (action.equals("rfcommUnListen")) {
            String name = Tools.getData(json, Tools.NAME);
            String uuidstr = Tools.getData(json, Tools.UUID);
            BluetoothSerialService service = acceptServices.get(name + uuidstr);
            if (service != null) {
                service.stop();
            }
        }
        if (action.equals("rfcommWrite")) {
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            BluetoothSerialService service = classicalServices.get(deviceAddress);
            if (service != null) {
                String data = Tools.getData(json, Tools.WRITE_VALUE);
                service.write(Tools.decodeBase64(data));
                callbackContext.success();
            } else {
                callbackContext.error("there is no connection on device:" + deviceAddress);
            }
        }
        if (action.equals("rfcommRead")) {
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            BluetoothSerialService service = classicalServices.get(deviceAddress);
            if (service != null) {
                byte[] data = new byte[2048];
                byte[] predata = service.buffer.array();
                for (int i = 0; i < service.bufferSize; i++) {
                    data[i] = predata[i];
                }

                JSONObject obj = new JSONObject();
                //Tools.addProperty(obj, Tools.DEVICE_ADDRESS, deviceAddress);
                Tools.addProperty(obj, Tools.VALUE, Tools.encodeBase64(data));
                Tools.addProperty(obj, Tools.DATE, Tools.getDateString());
                callbackContext.success(obj);
                service.bufferSize = 0;
                service.buffer.clear();
            } else {
                callbackContext.error("there is no connection on device:" + deviceAddress);
            }
        }
        if (action.equals("rfcommSubscribe")) {
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            BluetoothSerialService service = classicalServices.get(deviceAddress);
            if (service != null) {
                service.dataAvailableCallback = callbackContext;
            } else {
                callbackContext.error("there is no connection on device:" + deviceAddress);
            }
        }
        if (action.equals("rfcommUnsubscribe")) {
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            BluetoothSerialService service = classicalServices.get(deviceAddress);
            if (service != null) {
                service.dataAvailableCallback = null;
            } else {
                callbackContext.error("there is no connection on device:" + deviceAddress);
            }
        }
        if (action.equals("getPairedDevices")) {
            try {
                Log.i(TAG, "getPairedDevices");
                JSONArray ary = new JSONArray();
                Set<BluetoothDevice> devices = bluetoothAdapter.getBondedDevices();
                Iterator<BluetoothDevice> it = devices.iterator();
                while (it.hasNext()) {
                    BluetoothDevice device = (BluetoothDevice) it.next();
                    JSONObject obj = new JSONObject();
                    Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
                    Tools.addProperty(obj, Tools.DEVICE_NAME, device.getName());
                    ary.put(obj);
                }
                callbackContext.success(ary);
            } catch (Exception e) {
                Tools.sendErrorMsg(callbackContext);
            } catch (java.lang.Error e) {
                Tools.sendErrorMsg(callbackContext);
            }
        } else if (action.equals("createPair")) {
            Log.i(TAG, "createPair");
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            JSONObject obj = new JSONObject();
            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
            if (Tools.creatBond(device.getClass(), device)) {
                Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
                callbackContext.success(obj);
            } else {
                Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
                callbackContext.error(obj);
            }
        } else if (action.equals("removePair")) {
            Log.i(TAG, "removePair");
            String deviceAddress = Tools.getData(json, Tools.DEVICE_ADDRESS);
            JSONObject obj = new JSONObject();
            BluetoothDevice device = bluetoothAdapter.getRemoteDevice(deviceAddress);
            if (Tools.removeBond(device.getClass(), device)) {
                Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
                callbackContext.success(obj);
            } else {
                Tools.addProperty(obj, Tools.DEVICE_ADDRESS, device.getAddress());
                callbackContext.error(obj);
            }
        }
    } catch (Exception e) {
        Tools.sendErrorMsg(callbackContext);
    } catch (Error e) {
        Tools.sendErrorMsg(callbackContext);
    }
    return true;
}

From source file:com.chaosinmotion.securechat.server.json.DeviceReturnResult.java

public JSONObject returnData() {
    JSONArray array = new JSONArray();
    for (JSONObject m : devices) {
        array.put(m);// www .j a v a  2s  .c o  m
    }

    JSONObject obj = new JSONObject();
    obj.put("devices", array);
    obj.put("userid", userid);
    return obj;
}

From source file:com.mirasense.scanditsdk.plugin.SubViewPickerController.java

@Override
public void didEnter(String entry) {
    PluginResult result;/*from   w ww.j ava  2 s  . c om*/
    if (mLegacyMode) {
        JSONArray args = new JSONArray();
        args.put(entry);
        args.put("UNKNOWN");
        result = Marshal.createOkResult(args);
    } else {
        JSONArray args = Marshal.createEventArgs(ScanditSDK.DID_MANUAL_SEARCH_EVENT, entry);
        result = Marshal.createOkResult(args);
    }
    mCallbackContext.sendPluginResult(result);
    if (!mContinuousMode) {
        this.close();
    }

}

From source file:com.mirasense.scanditsdk.plugin.SubViewPickerController.java

@Override
public void didScan(ScanSession session) {
    // don't do anything if there is a pending close operation. otherwise we will deadlock
    if (mPendingClose.get()) {
        return;/*from  w w w  .  j a v  a 2  s.  c  o  m*/
    }
    PluginResult result;
    if (mLegacyMode) {
        JSONArray args = new JSONArray();
        Barcode code = session.getNewlyRecognizedCodes().get(0);
        args.put(code.getData());
        args.put(Code.symbologyToString(code.getSymbology(), code.isGs1DataCarrier()));
        args.put(code.getSymbologyName());
        result = Marshal.createOkResult(args);
    } else {
        JSONArray eventArgs = Marshal.createEventArgs(ScanditSDK.DID_SCAN_EVENT,
                ResultRelay.jsonForSession(session));
        result = Marshal.createOkResult(eventArgs);
    }

    int nextState = sendPluginResultBlocking(result);
    if (!mContinuousMode) {
        nextState = PickerStateMachine.PAUSED;
    }
    mPickerStateMachine.switchToNextScanState(nextState, session);
    Marshal.rejectCodes(session, mRejectedCodeIds);
    if (!mContinuousMode) {
        removeSubviewPicker();
    }
}

From source file:com.comcast.oscar.ber.OIDToJSONArray.java

/**
 *
 * @return JSON Array of the OID, DataType and Value */
public JSONArray toJSONArray() {

    JSONArray jaOID = new JSONArray();

    JSONObject joOID = new JSONObject();

    try {//from  w w w  . ja  v a  2 s .  co m

        this.sOID = this.sOID.replaceAll("^\\.", "");

        joOID.put(OID, this.sOID);

        joOID.put(DATA_TYPE, this.sDataType);

        //Clean up double quotes in the from and end of string
        this.sValue = this.sValue.replaceAll("^\"|\"$", "");
        joOID.put(VALUE, this.sValue);

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

    return jaOID.put(joOID);
}

From source file:de.dmxcontrol.model.BaseModel.java

protected void SendData(String propertyType, Object valueType, Object value) throws JSONException {

    JSONArray array = new JSONArray();
    for (int i = 0; i < ReceivedData.get().Devices.size(); i++) {
        if (getEntitySelection().contains(EntityManager.Type.DEVICE,
                ReceivedData.get().Devices.get(i).getId())) {
            array.put(ReceivedData.get().Devices.get(i).guid);
        }/* www  . j a va  2s  . c  o m*/
    }
    for (int i = 0; i < ReceivedData.get().Groups.size(); i++) {
        if (getEntitySelection().contains(EntityManager.Type.GROUP, ReceivedData.get().Groups.get(i).getId())) {
            array.put(ReceivedData.get().Groups.get(i).guid);
        }
    }

    JSONObject o = new JSONObject();
    o.put("Type", "PropertyValue");
    o.put("GUIDs", array);
    o.put("PropertyType", propertyType);
    o.put("ValueType", valueType);
    o.put("Value", value);

    ServiceFrontend.get().sendMessage(o.toString().getBytes());
}

From source file:com.ubikod.capptain.android.sdk.reach.CapptainPoll.java

/**
 * Parse an announcement.//from  w  w w  . ja v  a  2s .  c  o  m
 * @param jid service that sent the announcement.
 * @param xml raw XML of announcement to store in SQLite.
 * @param root parsed XML root DOM element.
 * @throws JSONException if a parsing error occurs.
 */
CapptainPoll(String jid, String xml, Element root) throws JSONException {
    super(jid, xml, root);
    mAnswers = new Bundle();
    mQuestions = new JSONArray();
    NodeList questions = root.getElementsByTagNameNS(REACH_NAMESPACE, "question");
    for (int i = 0; i < questions.getLength(); i++) {
        Element questionE = (Element) questions.item(i);
        NodeList choicesN = questionE.getElementsByTagNameNS(REACH_NAMESPACE, "choice");
        JSONArray choicesJ = new JSONArray();
        for (int j = 0; j < choicesN.getLength(); j++) {
            Element choiceE = (Element) choicesN.item(j);
            JSONObject choiceJ = new JSONObject();
            choiceJ.put("id", choiceE.getAttribute("id"));
            choiceJ.put("title", XmlUtil.getText(choiceE));
            choiceJ.put("default", Boolean.parseBoolean(choiceE.getAttribute("default")));
            choicesJ.put(choiceJ);
        }
        JSONObject questionJ = new JSONObject();
        questionJ.put("id", questionE.getAttribute("id"));
        questionJ.put("title", XmlUtil.getTagText(questionE, "title", null));
        questionJ.put("choices", choicesJ);
        mQuestions.put(questionJ);
    }
}