gpt4 book ai didi

android - 如何使用 Android 代码从 JSON 响应中获取特定值?

转载 作者:行者123 更新时间:2023-11-29 17:45:48 26 4
gpt4 key购买 nike

我需要获取特定对象值(A、B、C、D)和相关键值 (@"name")。获取 (A, B, C, D ) 对象值后,我需要将其列出到 ListView Android 中。下面我发布了我的示例代码和响应。请帮助我。

@Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();

// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);

if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);

contacts = jsonObj.getJSONArray("response");
Log.d("Response: ", "> " + contacts);

// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);

}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}

return null;
}

我的 JSON 响应:

{"response" : [  {

"A" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
],

"B" : [ {
"name" : "tango"
},
{
"name" : "ping"
}
]
} ]}

最佳答案

使用JSONObject keys()获取 key ,然后迭代每个 key 以获取动态值。

你可以获得这样的动态 key

JSONObject responseDataObj = new JSONObject(responseData);
JSONArray responseArray = responseDataObj.getJSONArray("response");
for (int i = 0; i < responseArray.length(); i++) {
nodes = new ArrayList<ArrayList<String>>();//nodes ArrayList<ArrayList<String>> declared globally
nodeSize = new ArrayList<Integer>();//nodeSize ArrayList<Integer> declared globally
JSONObject obj = responseArray.getJSONObject(i);
Iterator keys = obj.keys();
while(keys.hasNext()) {
// loop to get the dynamic key
String currentDynamicKey = (String)keys.next();
//store key in an arraylist which is A,B,...
// get the value of the dynamic key
JSONArray currentDynamicValue = obj.getJSONArray(currentDynamicKey);
int jsonrraySize = currentDynamicValue.length();
int sizeInArrayList = jsonrraySize + 1;
nodeSize.add(sizeInArrayList);
if(jsonrraySize > 0) {
for (int ii = 0; ii < jsonrraySize; ii++) {
nameList = new ArrayList<String>();//nameList ArrayList<String> declared globally
if(ii == 0) {
JSONObject nameObj = currentDynamicValue.getJSONObject(ii);
String name = nameObj.getString("name");
System.out.print("Name = " + name);
//store name in an arraylist
nameList.add(name);
}
}
}
nodes.add(nameList);
}
}

关于android - 如何使用 Android 代码从 JSON 响应中获取特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26837541/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com