如何从Android中的发布请求响应中获取特定的json键值? [英] How to get a specific json key value from post request response in Android?
本文介绍了如何从Android中的发布请求响应中获取特定的json键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我收到来自使用HttpURLConnection
的发帖请求的以下响应:
I have following response from post request using HttpURLConnection
:
发布请求响应:
{
"LatestData": [{
"ExtraData": null,
"ID": 0,
"season": false,
"latest": 0,
"url": "http://www.awebsite.com/images/12.jpg"
}]
}
如何获取URL的价值?我尝试了以下操作,但Android Studio不断给我错误:
How to get value of URL? I tried following but Android Studio keeps giving me error:
String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
Android Studio错误:
Android Studio Error:
error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
你们能帮我获得url的值,并让我知道我需要导入到android studio的哪些库,以便getsonObject可以工作吗?谢谢
could you guys help me obtain the value of url and let me know what libraries i need to import to android studio so getsonObject works ?Thanks
android代码:
android code:
if (myURLConnection.getResponseCode() == 200) {
br = new BufferedReader(new InputStreamReader(myURLConnection.getInputStream(), "utf-8"));
while (true) {
line = br.readLine();
if (line != null) {
sb.append(line + "\n");
//String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL =sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
mWebView.loadUrl("javascript:MyFunction('" +newURL + "');");
} else {
br.close();
return sb.toString();
}
}
}
推荐答案
您需要将sb转换为JSONObject才能访问属性:
You need to convert sb to a JSONObject to access properties:
JSONOjbect jsonResponse = new JSONObject(new String(sb));
然后:
try {
JSONArray jsonArray = jsonResponse.getJSONArray("LatestData");
if (jsonArray != null && jsonArray.length() > 0) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject dataOjbect = jsonArray.getJSONObject(i);
String url = dataOjbect.getString("url");
}
}
} catch (Exception e) {
e.printStackTrace();
}
这篇关于如何从Android中的发布请求响应中获取特定的json键值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文