在我解析json json array
之前,但是这个json对象。它它让我陷入停顿。我怎么能像这样解析json:
{ "test1": {
"1": {
"action": "0",
"type": "1",
"id": "1",
},
"2": {
"action": "0",
"type": "1",
"id": "2",
}
},
"test2": {
"1": {
"id": "1",
"name": "one"
},
"2": {
"id": "2",
"name": "two"
},
"5": {
"id": "5",
"name": "three"
}
}}
答案 0 :(得分:2)
当您没有一组固定的密钥时,您已经预先知道,解析它的唯一方法是使用keys()
。它返回Iterator
,其中包含JSONObject
中包含的键。在你的情况下你可以有
JSONObject jsonObject = new JSONObject(...);
Iterator<String> iterator = jsonObject.keys();
while(iterator.hasNext()) {
String currentKey = iterator.next();
JSONObject obj = jsonObject.optJSONObject(key);
if (obj != null) {
Iterator<String> iterator2 = obj.keys();
}
}
iterator
将返回test1
和test2
,iterator2
将返回1
和2
,test1
和{ {1}},1
,2
5
答案 1 :(得分:0)
您可以创建一个JSONObject From字符串,如下所示
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
并解析jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
获取字符串值
String action = oneTest1Json.getString("action");
String type = oneTest1Json.getString("type");
String id = oneTest1Json.getString("id");
Log.d("Json parse","action -"+action+" type -"+type+" id -"+id);
如果需要JSONArray
,您可以尝试
public JSONArray getJsonArray (JSONObject jsonObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray = new JSONArray();
for (int i = 0; i < nameJsonArray.length(); i++) {
try {
String key = nameJsonArray.getString(i);
jsonArray.put(jsonObject.getString(key));
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonArray;
}
以防密钥如test1,test2,test3 ......
JSONObject jsonObject = new JSONObject("{'test1':'Kasun', 'test2':'columbo','test3': '29'}");
JSONArray jsonArray = new JSONArray();
for (int i = 1; i <= jsonObject.names().length(); i++) {
try{
jsonArray.put(jsonObject.getString("test" + i));
}catch (JSONException e){
e.printStackTrace();
}
你可以通过这种方式获得JSONArray
。