java 从json获取键名和键值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32875874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 20:54:37  来源:igfitidea点击:

get key name & key value from json

javajsoncordova

提问by Justin Young

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

我对java完全陌生。如何获取此 jsonobject 的键名和键值并将其传递给我的增量方法?

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;
}

回答by iperezmel78

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));
}

回答by Deepak Baliga

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.

由于您刚接触 Java,而 JSON 是目前最著名的数据交换语言之一,我建议您通过本示例彻底了解 JSON 的解析和结构。

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

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

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

这将为您获取 JSON 中的一组键。