在我解析JSON JSON数组
,但是这个JSON对象。它的这把我陷入瘫痪。我怎么可以解析JSON是这样的:
{测试1:{
1:{
行动:0,
类型:1,
ID:1,
},
2:{
行动:0,
类型:1,
ID:2,
}
},
测试2:{
1:{
ID:1,
名:一
},
2:{
ID:2,
名:两节
},
5:{
ID:5,
名:三化
}
}}
解决方案
您可以将创建一个JSONObject从字符串作为波纹管
的JSONObject的JSONObject =新的JSONObject(YOUR_JSON_STRING);
和解析的JSONObject
的JSONObject test1Json = jsonObject.getJSONObject(测试1);
的JSONObject oneTest1Json = test1Json.getJSONObject(1);
要获得字符串值
串动= oneTest1Json.getString(行动);
字符串类型= oneTest1Json.getString(类);
字符串ID = oneTest1Json.getString(ID);
Log.d(Json的解析,行动 - +动作+型 - +类型+号 - + ID);
如果需要他们为 JSONArray
的你可以尝试
公共JSONArray getJsonArray(JSONObject的的JSONObject){
JSONArray nameJsonArray = jsonObject.names();
JSONArray jsonArray =新JSONArray();
的for(int i = 0; I< nameJsonArray.length();我++){
尝试 {
字符串键= nameJsonArray.getString(我);
jsonArray.put(jsonObject.getString(键));
}赶上(JSONException E){
e.printStackTrace();
}
}
返回jsonArray;
}
在这样的test1情况下键,TEST2,TEST3 ...
的JSONObject的JSONObject =新的JSONObject({测试1:Kasun,测试2:科伦坡,TEST3':'29'});
JSONArray jsonArray =新JSONArray();
的for(int i = 1; I< = jsonObject.names()长度();我++){
尝试{
jsonArray.put(jsonObject.getString(测试+ i)段);
}赶上(JSONException E){
e.printStackTrace();
}
你可以得到你的 JSONArray
这样的。
Before I parse json json array
, but this json object. Its It drove me to a standstill. How i can parse json like this:
{ "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"
}
}}
解决方案
You can create a JSONObject From string as bellow
JSONObject jsonObject = new JSONObject(YOUR_JSON_STRING);
and to parse the jsonObject
JSONObject test1Json = jsonObject.getJSONObject("test1");
JSONObject oneTest1Json = test1Json.getJSONObject("1");
to get String values
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);
if need them as JSONArray
the you can try
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;
}
in case keys like 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();
}
you can get your JSONArray
this way.