从JSONObject获取Key和值 [英] Get Key and values from JSONObject
本文介绍了从JSONObject获取Key和值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试从我的JSONObject中提取Key和值。但我无法做到这一点。这是JSON:
I am trying to extract Key and values from my JSONObject. But i am not able to do that. Here is the JSON:
[{"id":["5"]},{"Tech":["Java"]}]
最初是一个字符串。我使用以下方法将其转换为JSONObject:
It is a String initially. I have converted that to JSONObject using :
JSONObject jsonObj = new JSONObject("[{"id":["5"]},{"Tech":["Java"]}]");
然后我想通过以下方式获取密钥和价值:
Then i am trying to get the key and value by:
jsonObj.getString("id");
但它给我null。任何人都可以帮我吗?
But its giving me null. Can anyone help me out here?
推荐答案
试试这个:
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();
}
这篇关于从JSONObject获取Key和值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文