Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get key name & key value from json

Tags:

java

json

cordova

I'm totally new to java. How do I get the key name & key value of this jsonobject & pass it to my increment method?

args = {'property_name':1}


private boolean handlePeopleIncrement(JSONArray args, final CallbackContext cbCtx) {

    JSONObject json_array = args.optJSONObject(0);

    mixpanel.getPeople().increment(key_name, key_value);
    cbCtx.success();
    return true;
}

UPDATE

Now I'm getting the error:

Object cannot be converted to Number  
Number value = json_array.get(key);

-

private boolean handlePeopleIncrement(JSONArray args, final CallbackContext cbCtx) {
     JSONObject json_array = args.optJSONObject(0);

    Iterator<?> keys = json_array.keys();

    while( keys.hasNext() ) {
        String key = (String) keys.next();
        Number value = json_array.get(key);
       // System.out.println("Key: " + key);
       // System.out.println("Value: " + json_array.get(key));
    }

    mixpanel.getPeople().increment(key, value);
    cbCtx.success();
    return true;
}
like image 206
Justin Young Avatar asked Sep 30 '15 21:09

Justin Young


2 Answers

Try using this

JSONObject json_array = args.optJSONObject(0);

Iterator<?> keys = json_array.keys();

while( keys.hasNext() ) {
    String key = (String) keys.next();
    System.out.println("Key: " + key);
    System.out.println("Value: " + json_array.get(key));
}
like image 55
iperezmel78 Avatar answered Oct 05 '22 10:10

iperezmel78


as your new to Java and JSON is one of the most famous data interchange language out there, I recommend you to understand the parsing and the structure of JSON thoroughly this example.

for (String key: jsonObject.keySet()){ System.out.println(key); }

This will fetch you the set of Keys in the JSON.

like image 43
Deepak Baliga Avatar answered Oct 05 '22 09:10

Deepak Baliga