Example usage for org.json JSONObject put

List of usage examples for org.json JSONObject put

Introduction

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

Prototype

public JSONObject put(String key, Object value) throws JSONException 

Source Link

Document

Put a key/value pair in the JSONObject.

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 ww. j  a  v a  2 s .  c om

    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:fr.arnaudguyon.xmltojsonlib.XmlToJson.java

private void putContent(String path, JSONObject json, String tag, String content) {
    try {//from w ww  . j a v  a  2s . co m
        // checks if the user wants to force a class (Int, Double... for a given path)
        Class forcedClass = mForceClassForPath.get(path);
        if (forcedClass == null) { // default behaviour, put it as a String
            if (content == null) {
                content = DEFAULT_EMPTY_STRING;
            }
            json.put(tag, content);
        } else {
            if (forcedClass == Integer.class) {
                try {
                    Integer number = Integer.parseInt(content);
                    json.put(tag, number);
                } catch (NumberFormatException exception) {
                    json.put(tag, DEFAULT_EMPTY_INTEGER);
                }
            } else if (forcedClass == Long.class) {
                try {
                    Long number = Long.parseLong(content);
                    json.put(tag, number);
                } catch (NumberFormatException exception) {
                    json.put(tag, DEFAULT_EMPTY_LONG);
                }
            } else if (forcedClass == Double.class) {
                try {
                    Double number = Double.parseDouble(content);
                    json.put(tag, number);
                } catch (NumberFormatException exception) {
                    json.put(tag, DEFAULT_EMPTY_DOUBLE);
                }
            } else if (forcedClass == Boolean.class) {
                if (content == null) {
                    json.put(tag, DEFAULT_EMPTY_BOOLEAN);
                } else if (content.equalsIgnoreCase("true")) {
                    json.put(tag, true);
                } else if (content.equalsIgnoreCase("false")) {
                    json.put(tag, false);
                } else {
                    json.put(tag, DEFAULT_EMPTY_BOOLEAN);
                }
            }
        }

    } catch (JSONException exception) {
        // keep continue in case of error
    }
}

From source file:de.decoit.visa.http.ajax.handlers.ConfigureHandler.java

@Override
public void handle(HttpExchange he) throws IOException {
    log.info(he.getRequestURI().toString());

    // Get the URI of the request and extract the query string from it
    QueryString queryParameters = new QueryString(he.getRequestURI());

    // Create StringBuilder for the response
    String response = null;/*w  w w.j  av a 2 s  . c o m*/

    // Check if the query parameters are valid for this handler
    if (this.checkQueryParameters(queryParameters)) {
        try {
            // Close any existing connection to IO-Tool, this handler is
            // called on reload of the frontend
            try {
                TEBackend.closeIOConnector(false);
            } catch (IOToolException iote) {
                log.warn("Cannot close connection to the IO-Tool, using connection from old session");
            }

            // Process document root parameter
            String docRoot = queryParameters.get("documentRoot").get();

            // Set export directory
            StringBuilder sbExportPath = new StringBuilder(docRoot);
            if (!docRoot.endsWith("/")) {
                sbExportPath.append("/");
            }
            sbExportPath.append("export/");

            TEBackend.setExportPath(sbExportPath.toString());

            // Set import directory
            StringBuilder sbImportPath = new StringBuilder(docRoot);
            if (!docRoot.endsWith("/")) {
                sbImportPath.append("/");
            }
            sbImportPath.append("import/");

            TEBackend.setImportPath(sbImportPath.toString());

            // Process rows and cols parameter
            int rows = Integer.parseInt(queryParameters.get("rows").get());
            int cols = Integer.parseInt(queryParameters.get("cols").get());

            TEBackend.setGridDimensions(cols, rows);
            TEBackend.TOPOLOGY_STORAGE.getComponentGroupByName("0.0.0.0").setSubgridDimensions(cols, rows);

            // Process cell size parameter
            int cSize = Integer.parseInt(queryParameters.get("csize").get());

            TEBackend.setCellSize(cSize);

            // Process component margin parameter
            int compMargin = Integer.parseInt(queryParameters.get("compMargin").get());

            TEBackend.setComponentMargin(compMargin);

            // Return success response
            JSONObject rv = new JSONObject();
            rv.put("status", AJAXServer.AJAX_SUCCESS);
            rv.put("vsatemplates", TEBackend.RDF_MANAGER.vsaTemplatesToJSON());
            response = rv.toString();
        } catch (Throwable ex) {
            TEBackend.logException(ex, log);

            // Exception was thrown during configuration
            JSONObject rv = new JSONObject();

            try {
                rv.put("status", AJAXServer.AJAX_ERROR_EXCEPTION);
                rv.put("type", ex.getClass().getSimpleName());
                rv.put("message", ex.getMessage());
            } catch (JSONException exc) {
                /* Ignore */
            }

            response = rv.toString();
        }
    } else {
        // Missing or malformed query string, set response to error code
        JSONObject rv = new JSONObject();
        try {
            // Missing or malformed query string, set response to error code
            rv.put("status", AJAXServer.AJAX_ERROR_MISSING_ARGS);
        } catch (JSONException exc) {
            /* Ignore */
        }

        response = rv.toString();
    }

    // Send the response
    sendResponse(he, response);
}

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

private void getGenes() {
    MLQueryManager.findAllInBackground(query, new FindCallback<MLObject>() {
        @Override//from  www.ja  v a 2  s.  c om
        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/*  www  . ja v a 2s  .  c  om*/
        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 {/*  www  . j a  va 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 void addDeviceUUID(String uuid, String publicKey) {
    JSONObject json = new JSONObject();
    json.put("deviceid", uuid);
    json.put("publickey", publicKey);
    devices.add(json);/*w  ww . j a va2 s.c  o m*/
}

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

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

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

From source file:io.github.minime89.passbeam.keyboard.Scancode.java

public JSONObject dump() throws JSONException {
    JSONObject obj = new JSONObject();
    if (!cycle) {
        cycle = true;/*from w ww. j  a  v a 2 s . c  om*/
        try {
            obj.put("value", value);
            obj.put("name", name);
            obj.put("keycodeRef", (keycodeRef != null) ? keycodeRef.dump() : null);
            obj.put("keycode", (keycode != null) ? keycode.dump() : null);
        } finally {
            cycle = false;
        }
    }

    return obj;
}

From source file:org.hypertopic.RESTDatabaseTest.java

/**
 * Note: success depends on create/*w ww . ja  va  2 s. co  m*/
 */
@Test
public void updateOnCouch() throws Exception {
    JSONObject o = new JSONObject().put("name", "Bond");
    this.db.post(o);
    this.db.put(o.put("name", "James Bond"));
}