Example usage for org.json JSONObject keys

List of usage examples for org.json JSONObject keys

Introduction

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

Prototype

public Iterator keys() 

Source Link

Document

Get an enumeration of the keys of the JSONObject.

Usage

From source file:com.trk.aboutme.facebook.model.JsonUtil.java

static Collection<Object> jsonObjectValues(JSONObject jsonObject) {
    ArrayList<Object> result = new ArrayList<Object>();

    @SuppressWarnings("unchecked")
    Iterator<String> keys = (Iterator<String>) jsonObject.keys();
    while (keys.hasNext()) {
        result.add(jsonObject.opt(keys.next()));
    }/*from  ww  w  .j  a  v a  2s  . c om*/

    return result;
}

From source file:com.atinternet.tracker.Tool.java

/**
 * Convert a JSONObject to Map/*from   w w w .  j  a v a2s. c  o  m*/
 *
 * @param jsonObject JSONObject
 * @return Map
 */
static Map toMap(JSONObject jsonObject) {
    Map<String, Object> map = new HashMap<String, Object>();

    Iterator<String> keysItr = jsonObject.keys();
    while (keysItr.hasNext()) {
        String key = keysItr.next();
        Object value = null;
        try {
            value = jsonObject.get(key);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        map.put(key, value);
    }
    return map;
}

From source file:com.yanzhenjie.nohttp.HttpHeaders.java

@Override
public void setJSONString(String jsonString) throws JSONException {
    clear();/*from w  w  w . jav a 2  s.c  o  m*/
    JSONObject jsonObject = new JSONObject(jsonString);
    Iterator<String> keySet = jsonObject.keys();
    while (keySet.hasNext()) {
        String key = keySet.next();
        String value = jsonObject.optString(key);
        JSONArray values = new JSONArray(value);
        for (int i = 0; i < values.length(); i++)
            add(key, values.optString(i));
    }
}

From source file:com.jaspersoft.jasperserver.ps.OAuth.JSONUtils.java

private static Map<String, String> parse(JSONObject json, Map<String, String> out) throws JSONException {
    Iterator<String> keys = json.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        String val = null;
        try {/* ww w. ja  v  a 2 s .com*/
            JSONObject value = json.getJSONObject(key);
            parse(value, out);
        } catch (Exception e) {
            val = json.getString(key);
        }

        if (val != null) {
            out.put(key, val);
        }
    }
    return out;
}

From source file:com.nextgis.maplib.datasource.ngw.Connection.java

protected void fillCapabilities() {
    mSupportedTypes.clear();/*  w  w  w  .j  ava  2 s.  co m*/
    try {
        String sURL = mURL + "/resource/schema";
        HttpGet get = new HttpGet(sURL);
        get.setHeader("Cookie", getCookie());
        get.setHeader("Accept", "*/*");
        HttpResponse response = getHttpClient().execute(get);
        HttpEntity entity = response.getEntity();

        JSONObject schema = new JSONObject(EntityUtils.toString(entity));
        JSONObject resources = schema.getJSONObject("resources");
        if (null != resources) {
            Iterator<String> keys = resources.keys();
            while (keys.hasNext()) {
                int type = getType(keys.next());
                if (type != NGWResourceTypeNone) {
                    if (mSupportedTypes.isEmpty())
                        mSupportedTypes.add(type);
                    else if (!isTypeSupported(type))
                        mSupportedTypes.add(type);
                }
            }
        }
    } catch (IOException | JSONException e) {
        e.printStackTrace();
    }
}

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

private void format(JSONObject jsonObject, StringBuilder builder, String indent) {
    Iterator<String> keys = jsonObject.keys();
    while (keys.hasNext()) {
        String key = keys.next();
        builder.append(indent);//from w  ww . j av a2s . c  om
        builder.append(mIndentationPattern);
        builder.append("\"");
        builder.append(key);
        builder.append("\": ");
        Object value = jsonObject.opt(key);
        if (value instanceof JSONObject) {
            JSONObject child = (JSONObject) value;
            builder.append(indent);
            builder.append("{\n");
            format(child, builder, indent + mIndentationPattern);
            builder.append(indent);
            builder.append(mIndentationPattern);
            builder.append("}");
        } else if (value instanceof JSONArray) {
            JSONArray array = (JSONArray) value;
            formatArray(array, builder, indent + mIndentationPattern);
        } else {
            formatValue(value, builder);
        }
        if (keys.hasNext()) {
            builder.append(",\n");
        } else {
            builder.append("\n");
        }
    }
}

From source file:com.citrus.sdk.payment.PaymentBill.java

public static PaymentBill fromJSON(String json) {
    PaymentBill paymentBill = null;//w  w w .jav a  2  s  .  c o m

    JSONObject billObject = null;
    try {
        billObject = new JSONObject(json);
    } catch (JSONException e) {
        e.printStackTrace();
    }

    if (billObject != null) {
        Amount amount = null;
        String requestSignature = null;
        String merchantTransactionId = null; // TODO: Do the validation of the transaction id length
        String merchantAccessKey = null;
        String returnUrl = null;
        String notifyUrl = null;
        Map<String, String> customParametersMap = null;

        amount = Amount.fromJSONObject(billObject.optJSONObject("amount"));
        requestSignature = billObject.optString("requestSignature");
        merchantTransactionId = billObject.optString("merchantTxnId");
        merchantAccessKey = billObject.optString("merchantAccessKey");
        returnUrl = billObject.optString("returnUrl");
        notifyUrl = billObject.optString("notifyUrl");

        JSONObject customParamsObject = billObject.optJSONObject("customParameters");
        if (customParamsObject != null) {
            customParametersMap = new HashMap<>();
            Iterator<String> iter = customParamsObject.keys();
            while (iter.hasNext()) {
                String key = iter.next();
                String value = customParamsObject.optString(key);

                customParametersMap.put(key, value);
            }
        }

        if (amount != null && requestSignature != null && returnUrl != null && merchantAccessKey != null
                && merchantTransactionId != null) {

            paymentBill = new PaymentBill(amount, requestSignature, merchantTransactionId, merchantAccessKey,
                    returnUrl, notifyUrl, customParametersMap);
        }
    }

    return paymentBill;
}

From source file:com.example.wmgps.MainActivity.java

/** Called when the user clicks the Send button */
public void sendMessage(View view) {
    /*Intent intent = new Intent(this, DisplayMessageActivity.class);
    EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
    intent.putExtra(EXTRA_MESSAGE, message);
    startActivity(intent);*//*  w  w  w  .ja v a2 s . co m*/

    /*EditText editText = (EditText) findViewById(R.id.edit_message);
    String message = editText.getText().toString();
            
    TextView output = (TextView) findViewById(R.id.welcome);
    output.setText(message);*/

    /*Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(URL));
    startActivity(browserIntent);
            
    */
    TextView hiddenText = (TextView) findViewById(R.id.Hidden11);
    if (Misc.isNullTrimmedString(hiddenText.getText().toString())) {
        TextView output = (TextView) findViewById(R.id.welcome1);
        boolean without_connection = true;
        Map<String, ArrayList<String>> typeAndValueOfTag = new LinkedHashMap<String, ArrayList<String>>(); // Insertion order must be followed

        String response = Misc.EMPTY_STRING;
        String welcome1String = "*******************Connected*************************";
        try {

            response = new RetrieveFeedTask().execute(new String[] {}).get();

        } catch (Exception e) {
            response = Misc.EMPTY_STRING;
            Log.e("Exception ", e.getMessage());

            Log.e("Exception ", e.getLocalizedMessage());

            Log.e("Exception ", e.getStackTrace().toString());

        }

        if (Misc.isNullTrimmedString(response)) {
            // welcome1String = "***Loading Static, couldn't connect***";

            response = "{\"window\":{\"elements\":[{\"type\":\"hidden\",\"name\":\"sourceAction\"},{\"type\":\"label\",\"value\":\"Warehouse Management\"},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"--------- ----------\"},{\"type\":\"break\"}, {\"type\":\"label\",\"value\":\" User ID: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_username\",\"value\":\"\",\"maxLength\":15,\"dispLength\":10,"
                    + "\"setHidden\":[{\"hiddenName\":\"sourceAction\",\"hiddenValue\":\"username\"}],\"focus\":true},"
                    + "{\"type\":\"break\"},{\"type\":\"label\",\"value\":\"Password: \"},"
                    + "{\"type\":\"entry\",\"name\":\"j_password\",\"value\":\"\",\"hideInput\":true,\"maxLength\":14,\"dispLength\":10,\"focus\":false},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-X\",\"URL\":\"\",\"keyDescription\":\"CTRL-X Exit\"},"
                    + "{\"type\":\"keybinding\",\"value\":\"CTRL-L\",\"URL\":\"/scopeRF/RFLogin/RFLegal.jsp\",\"keyDescription\":\"CTRL-L License Agreement\"}]"
                    + ",\"submit\":\"/scopeRF/RFLogin/ProcessLogin.jsp\"}}";
        }

        StringBuffer finalEncodedString = new StringBuffer(Misc.EMPTY_STRING);

        int currentOutputTag = R.id.Hidden1;
        int currentInputTag = R.id.edit_message;

        // Renderer::decodeConfig()
        if (!Misc.isNullTrimmedString(response)) {
            try {
                JSONObject jsonObj = new JSONObject(response);

                for (Iterator iterator = jsonObj.keys(); iterator.hasNext();) {
                    String name = (String) iterator.next();

                    JSONObject jsonObj1 = jsonObj.getJSONObject(name);

                    for (Iterator iterator1 = jsonObj1.keys(); iterator1.hasNext();) {
                        String name1 = (String) iterator1.next();

                        if ("elements".equals(name1)) {
                            JSONArray jsonArr = jsonObj1.getJSONArray(name1);
                            boolean userName = false;
                            boolean password = false;
                            for (int i = 0; i < jsonArr.length(); i++) {
                                JSONObject temp = jsonArr.getJSONObject(i);
                                String initialValue = null;
                                String initialName = null;
                                String initialLabel = null;

                                if (!temp.isNull("name") && temp.getString("name").equals("j_password")) {
                                    initialName = "j_password";
                                } else if (!temp.isNull("name")
                                        && temp.getString("name").equals("j_username")) {
                                    initialName = "j_username";
                                }

                                for (Iterator iterator2 = temp.keys(); iterator2.hasNext();) {
                                    String tempName = (String) iterator2.next();
                                    String tempValue = (String) temp.getString(tempName);

                                    if (tempName.equals("type")) {
                                        if (tempValue.equals("label") || tempValue.equals("entry")) {
                                            initialLabel = tempValue;
                                        }
                                    } else if (tempName.equals("value")) {
                                        initialValue = tempValue;
                                    }

                                    /* if(tempName.equals("label"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue))
                                     initialLabel = tempName;
                                        else
                                        {
                                     typeAndValueOfTag.put("output",initialValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                     }
                                     else if(tempName.equals("value"))
                                     {
                                        if(Misc.isNullTrimmedString(initialName) && Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialValue = tempValue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("label"))
                                        {
                                     typeAndValueOfTag.put("output",tempValue);
                                     initialValue = Misc.EMPTY_STRING;
                                     continue;
                                        }
                                        else if(!Misc.isNullTrimmedString(initialLabel) && initialLabel.equals("entry"))
                                        {
                                     if(!Misc.isNullTrimmedString(initialName) && initialName.equals("name"))
                                        typeAndValueOfTag.put("input",tempValue);
                                     else
                                        initialValue = tempValue;
                                        }
                                     }
                                     else if(tempName.equals("entry"))
                                     {
                                        if(Misc.isNullTrimmedString(initialValue) || Misc.isNullTrimmedString(initialLabel))
                                        {
                                     initialName = tempName;
                                        }
                                        else
                                     typeAndValueOfTag.put("input",initialValue);
                                                
                                        finalEncodedString.append("  " + tempName + "  " + tempValue + " ----- ");
                                     }*/
                                }

                                if (initialLabel != null) {
                                    if (initialLabel.equals("label")) {
                                        if (initialValue.equals(" User ID: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.userNameText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = true;
                                            password = false;
                                        } else if (initialValue.equals("Password: ")) {
                                            TextView output1 = (TextView) findViewById(R.id.passwordText);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            password = true;
                                            userName = false;
                                        } else {
                                            TextView output1 = (TextView) findViewById(currentOutputTag++);
                                            output1.setText(initialValue);
                                            output1.setVisibility(View.VISIBLE);
                                            userName = false;
                                            password = false;
                                        }
                                    } else if (initialLabel.equals("entry")) {
                                        if ("j_password".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.passwordEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter password");
                                            }
                                        } else if ("j_username".equals(initialName)) {
                                            EditText input = ((EditText) findViewById(R.id.userNameEdit));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter username");
                                            }
                                        } else {
                                            EditText input = ((EditText) findViewById(currentInputTag++));
                                            input.setVisibility(View.VISIBLE);
                                            if (Misc.isNullTrimmedString(initialValue)) {
                                                input.setText("");
                                                input.setHint("Please enter value");
                                            } else
                                                input.setText(initialValue);
                                        }
                                    }
                                }
                                /*if(initialLabel != null)
                                {
                                   List<String> listOfValues;
                                   if(typeAndValueOfTag.containsKey(initialLabel))
                                   {
                                  listOfValues = typeAndValueOfTag.get(initialLabel);
                                  listOfValues.add(initialValue);
                                   }
                                   typeAndValueOfTag.put(initialLabel,initialValue);
                                }*/
                            }
                        } else {
                            // Here, just the URL would get processed. So don't use.
                            // output.setText("  " + name + "  " + jsonObj1.getString(name1));
                        }
                    }
                }

                TextView welcome1 = (TextView) findViewById(R.id.welcome1);
                welcome1.setText(welcome1String);

                // processUIDisplay(typeAndValueOfTag);

                /*if(finalEncodedString.length() == 0)
                   finalEncodedString.append("Could not process");
                        
                output.setText(finalEncodedString.toString());
                        
                TextView output2 = (TextView) findViewById(R.id.Hidden1);
                output2.setText("Hidden one is enabled");
                output2.setVisibility(View.VISIBLE);*/

            } catch (JSONException e) {
                Log.e("Exception ", e.getMessage());

                Log.e("Exception ", e.getLocalizedMessage());

                Log.e("Exception ", e.getStackTrace().toString());
            }
        }

        hiddenText.setText("validated user");

        /* {"window":{"elements":[{"type":"hidden","name":"sourceAction"},{"type":"label","value":"Warehouse Management"},
                  {"type":"break"},{"type":"label","value":"--------- ----------"},{"type":"break"}, {"type":"label","value":" User ID: "},
                  {"type":"entry","name":"j_username","value":"","maxLength":15,"dispLength":10,
                  "setHidden":[{"hiddenName":"sourceAction","hiddenValue":"username"}],"focus":true},
                  {"type":"break"},{"type":"label","value":"Password: "},
                  {"type":"entry","name":"j_password","value":"","hideInput":true,"maxLength":14,"dispLength":10,"focus":false},
                  {"type":"keybinding","value":"CTRL-X","URL":"","keyDescription":"CTRL-X Exit"},
                  {"type":"keybinding","value":"CTRL-L","URL":"/scopeRF/RFLogin/RFLegal.jsp","keyDescription":"CTRL-L License Agreement"}]
           ,"submit":"/scopeRF/RFLogin/ProcessLogin.jsp"}}*/
    } else {
        List outputList = verifyUser();

        if (!Misc.isNullList(outputList)) {
            String sessionId = (String) outputList.get(0);
            String userType = (String) outputList.get(1);

            Intent intent = new Intent(this, MenuActivity.class);
            if (!Misc.isNullTrimmedString(sessionId) && !Misc.isNullTrimmedString(userType)
                    && Integer.parseInt(sessionId) > 0) {
                if (userType.equals(Constants.WORKER)) {
                    MenuActivity.sessionId = Misc.EMPTY_STRING;
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.WORKER);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                } else {
                    TextView error = (TextView) findViewById(R.id.ErrorText);
                    error.setText(Misc.EMPTY_STRING);
                    error.setVisibility(View.GONE);
                    intent.putExtra(Constants.USER_TYPE, Constants.SUPERVISOR);
                    intent.putExtra(Constants.SESSION_ID, sessionId);
                }
            }
            // goto Maps screen
            // Get the message from the intent
            startActivity(intent);
        } else {

            TextView error = (TextView) findViewById(R.id.ErrorText);
            error.setText("Invalid Username/Password");
            error.setVisibility(View.VISIBLE);
        }
    }
    return;

}

From source file:produvia.com.scanner.DevicesActivity.java

private void updateServiceDeviceDatabase(JSONObject data) {
    try {/*from  w w  w.ja  v a 2  s.co m*/
        //first add the services to the devices:
        JSONArray services = data.getJSONArray("services");
        for (int i = 0; i < services.length(); i++) {
            JSONObject service = services.getJSONObject(i);
            String device_id = service.getString("device_id");
            JSONObject device = data.getJSONObject("devices_info").getJSONObject(device_id);
            if (!device.has("services"))
                device.put("services", new JSONObject());
            device.getJSONObject("services").put(service.getString("id"), service);
        }

        JSONObject devices = data.getJSONObject("devices_info");
        //loop over the devices and merge them into the device display:
        for (Iterator<String> iter = devices.keys(); iter.hasNext();) {
            String device_id = iter.next();
            JSONObject device = devices.getJSONObject(device_id);
            //if a device card is already present - just merge the data:
            boolean found = false;
            int network_card_idx = -1;
            for (int i = 0; i < mDevices.size(); i++) {
                CustomListItem cli = mDevices.get(i);
                if (cli instanceof DeviceCard && ((DeviceCard) cli).getId().equals(device_id)) {
                    ((DeviceCard) cli).updateInfo(device);
                    found = true;
                    break;
                } else if (cli.getDescription().equals(device.getString("network_id"))) {
                    network_card_idx = i;
                }
            }

            if (!found) {
                if (network_card_idx < 0) {
                    JSONObject network = data.getJSONObject("networks_info")
                            .getJSONObject(device.getString("network_id"));
                    String name = "";
                    if (network.has("name") && network.getString("name") != null)
                        name = network.getString("name");
                    network_card_idx = addNetworkCard(name, device.getString("network_id"),
                            network.getBoolean("user_inside_network"));
                }
                network_card_idx += 1;
                //find the correct index for the card sorted by last seen:
                for (; network_card_idx < mDevices.size(); network_card_idx++) {
                    CustomListItem cli = mDevices.get(network_card_idx);
                    if (!(cli instanceof DeviceCard))
                        break;
                    if (((DeviceCard) cli).getLastSeen()
                            .compareTo(DeviceCard.getLastSeenFromString(device.getString("last_seen"))) < 0)
                        break;
                }

                DeviceCard dc = new DeviceCard(device);
                mDevices.add(network_card_idx, dc);
            }
        }
        notifyDataSetChanged();

    } catch (JSONException e) {
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
    }
}

From source file:org.zaizi.sensefy.api.utils.JSONHelper.java

@SuppressWarnings({ "unchecked", "rawtypes" })
public static Map<String, Object> toMap(JSONObject object) throws JSONException {
    Map<String, Object> map = new HashMap();
    Iterator keys = object.keys();
    while (keys.hasNext()) {
        String key = (String) keys.next();
        map.put(key, fromJson(object.get(key)));
    }//from  w w w  . j a  v  a 2 s. c o  m
    return map;
}