如何从Android中的发布请求响应中获取特定的json键值?

编程入门 行业动态 更新时间:2024-10-07 08:31:40
本文介绍了如何从Android中的发布请求响应中获取特定的json键值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我收到来自使用HttpURLConnection的发帖请求的以下响应:

I have following response from post request using HttpURLConnection:

发布请求响应:

{ "LatestData": [{ "ExtraData": null, "ID": 0, "season": false, "latest": 0, "url": "www.awebsite/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键值?

本文发布于:2023-11-26 21:42:03,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635301.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:键值   Android   json

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!