Java 从 JSONObject 获取键和值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42687615/
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-08-12 00:18:56  来源:igfitidea点击:

Get Key and values from JSONObject

javajson

提问by user7637864

I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:

我正在尝试从我的 JSONObject 中提取键和值。但我无法做到这一点。这是JSON:

[{"id":["5"]},{"Tech":["Java"]}]

It is a String initially. I have converted that to JSONObject using :

它最初是一个字符串。我已使用以下方法将其转换为 JSONObject:

JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");

Then i am trying to get the key and value by:

然后我试图通过以下方式获取键和值:

jsonObj.getString("id");

But its giving me null. Can anyone help me out here?

但它给我空。有人可以帮我从这里出去吗?

回答by Vipin Chaudhary

Because at idyou dont have a string , you have a array of string ,

因为id你没有一个字符串,你有一个字符串数组,

so insted of doing this jsonObj.getString("id");

所以不想这样做 jsonObj.getString("id");

do this

做这个

jsonObj.getArray("id");this will give you that array in return

jsonObj.getArray("id");这会给你那个数组作为回报

like if you have a Json Array at idthen you have to do this

就像如果你有一个 Json Arrayid那么你必须这样做

jsonObj.getJSONArray("id");

jsonObj.getJSONArray("id");

回答by wajih

Try this:

尝试这个:

try {
    JSONArray jsonArr = new JSONArray("[{\"id\":[\"5\"]},{\"Tech\":[\"Java\"]}]");

    for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
        String k = jsonObj.keys().next();
        Log.i("Info", "Key: " + k + ", value: " + jsonObj.getString(k));
    }

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

回答by AG_

Parameter you are sending is JsonArray and referring to JsonObject. The Correct way is

您发送的参数是 JsonArray 并引用 JsonObject。正确的做法是

JSONObject jsonObj = new JSONObject("{'id':['5','6']},{'Tech':['Java']}");      
    System.out.println(jsonObj.getString("id"));

    JSONArray jsonArray = new JSONArray("[{'id':['5','6','7','8']},{'Tech':['Java']}]");
    System.out.println(jsonArray.length());
    for(int i=0;i<jsonArray.length();i++){
            System.out.println(jsonArray.getJSONObject(i).getString("id"));
    }