我有一个动态的json响应,即使是键名和索引no.can也会改变
{
"Assigned": {
"DC": 7,
"EmpCode": "E0104",
"FS": 8
}
}
我想将它转换为JsonArray并在对象下动态获取所有键名称和值' Assigned'。但我只是通过尝试获取值名称。
try {
//converting dynamic jsonobject to json array and fetching value as well as key name
JSONObject jsonObject = response.getJSONObject("Assigned");
Iterator x = jsonObject.keys();
JSONArray jsonArray = new JSONArray();
while (x.hasNext()) {
String key = (String) x.next();
jsonArray.put(jsonObject.get(key));
}
Toast.makeText(RolesActivity.this,jsonArray.toString(), Toast.LENGTH_LONG).show();
Log.d("jsonarray",jsonArray.toString());
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(RolesActivity.this, e.toString(), Toast.LENGTH_SHORT).show();
}
答案 0 :(得分:1)
您可以致电JSONObject.keys()
(JSONObject
)或JSONObject.names()
(Iterator
)<来获取JSONArray
个键列表< / p>
之后,您可以遍历密钥,并使用JSONObject.getString(key)
答案 1 :(得分:0)
首先创建一个pojo类
private HashMap<String, String> parseResponse(){
String json = ""; // your json string
Gson gson = new Gson();
Response response = gson.fromJson(json, Response.class)
return response.getAssigned();
}
public class Response {
@SerializedName("Assigned")
private HashMap<String, String> assigned;
public HashMap<String, String> getAssigned() {
return assigned;
}
}
比用Gson库解析。您可以从指定的Hashmap中读取键和值。