如何在不知道密钥/名称字符串的情况下解码json?

时间:2012-12-09 13:24:37

标签: java android json

我收到以下格式的json字符串:

{"27":{"id":"27","uid":"4","title":"teamer.zapto.org","url":"www.google.jo","ip":"74.125.234.63","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058071"}},"fetch_interval":"60","ping_shift":"0"},

"30":{"id":"30","uid":"4","title":"google","url":"www.google.com","ip":"74.125.234.114","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058079"}},"fetch_interval":"60","ping_shift":"0"},

"31":{"id":"31","uid":"4","title":"facebook.com","url":"facebook.com","ip":"69.171.247.21","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058095"}},"fetch_interval":"60","ping_shift":"0"},

"32":{"id":"32","uid":"4","title":"ebir","url":"www.ebir.com","ip":"74.52.50.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058073"},"Http 1":{"status":"1","ts":"1355058073"}},"fetch_interval":"60","ping_shift":"0"},

"33":{"id":"33","uid":"4","title":"zapto","url":"teamer.zapto.org","ip":"200.35.150.6","enabled":"1","services":{"Http 1":{"status":"0","ts":"1355056146"}},"fetch_interval":"3600","ping_shift":"2"},

"35":{"id":"35","uid":"4","title":"vogella.com","url":"vogella.com","ip":"46.163.79.226","enabled":"1","services":{"Ftp":{"status":"1","ts":"1355058098"},"Http 1":{"status":"1","ts":"1355058098"}},"fetch_interval":"60","ping_shift":"0"},

"36":{"id":"36","uid":"4","title":"msn","url":"www.msn.com","ip":"131.253.13.140","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058103"}},"fetch_interval":"60","ping_shift":"0"},

"37":{"id":"37","uid":"4","title":"dubizzle.com","url":"www.dubizzle.com","ip":"94.236.93.152","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058068"}},"fetch_interval":"60","ping_shift":"0"},

"38":{"id":"38","uid":"4","title":"olx.jo","url":"olx.jo","ip":"204.74.99.100","enabled":"1","services":{"Http 1":{"status":"1","ts":"1355058108"}},"fetch_interval":"60","ping_shift":"0"},

"40":{"id":"40","uid":"4","title":"www.sukar.com","url":"www.sukar.com","ip":"72.52.8.195","enabled":"1","services":{"Ftp":{"status":"0","ts":"1355058092"},"Http 1":{"status":"1","ts":"1355058092"}},"fetch_interval":"60","ping_shift":"0"}}

你可以看到键是数字(27,30,31,...)并且不是连续的。如何从这样的json获取数据?我知道它必须是某种循环取决于长度,但我无法弄清楚如何这样做。通常我会使用jObject.getString("id"),但由于我不知道字符串是什么,我该怎么办?

2 个答案:

答案 0 :(得分:5)

如果您有JSONObject作为根,则应该能够执行以下操作:

JSONObject root = new JSONObject(jsonString);
JSONArray names = root.names();
for(int i = 0; i < names.length(); i++) {
    String tag = names.getString(i);
    ...
}

tag将是您引用的数字标记。

答案 1 :(得分:4)

JSONObject questionMark = new JSONObject(jsonString);
    Iterator keys = questionMark.keys();
while(keys.hasNext()) {
    // loop to get the dynamic key
    String currentDynamicKey = (String)keys.next();

    // get the value of the dynamic key
    JSONObject currentDynamicValue = questionMark.getJSONObject(currentDynamicKey);