![](/img/trans.png)
[英]How to both post request and get response (nested JSON) with retrofit android
[英]How to get a specific json key value from post request response in Android?
我收到以下來自使用HttpURLConnection
的請求的響應:
請求后回復:
{
"LatestData": [{
"ExtraData": null,
"ID": 0,
"season": false,
"latest": 0,
"url": "http://www.awebsite.com/images/12.jpg"
}]
}
如何獲得URL的價值? 我嘗試了以下操作,但Android Studio不斷給我錯誤:
String newURL = sb.getJSONObject("LatestData").getString("url");
String newURL = sb.getJSONArray("LatestData").getJSONObject(0).getString("url");
Android Studio錯誤:
error: cannot find symbol method getJSONObject(String)
error: cannot find symbol method getJSONArray(String)
你們可以幫助我獲取url的值並讓我知道我需要導入到android studio的哪些庫,以便getsonObject可以工作嗎?
android代碼:
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才能訪問屬性:
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();
}
try {
JSONObject jsonObject = new JSONObject(sb);
String url = jsonObject.optJSONArray("LatestData").getJSONObject(0).optString("url");
} catch (JSONException e) {
e.printStackTrace();
}
使用loadJSONArray
嘗試
String url = loadJSONArray(sb)..getJSONObject(0).getString("url");
您的方法應該是這樣的。
try {
List<String> urlist = new ArrayList<>();
JSONObject jsonObject = new JSONObject(sb.toString());
JSONArray jsonArray = jsonObject.getJSONArray("LatestData");
for (int count = 0; count<jsonArray.length(); count++){
JSONObject jsonInner = jsonArray.getJSONObject(count);
String url = jsonInner.getString("url");
//store your url in some list
urlist.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
你可以嘗試一下:
StringBuilder sb = new StringBuilder();
line = br.readLine();
while(line != null){
sb.append(line);
}
// if it's fail here then this means there is an issue in parsing JSONObject
JSONObject jsonObj = new JSONObject(sb.toString());
JSONArray latestData = jsonObj.getJSONArray("LatestData");
JSONObject jsonObject = latestData.getJSONObject(0);
String url = jsonObject.getString("url");
另外,我強烈建議對GSON使用Retrofit。您可以閱讀以下文章: http ://www.vogella.com/tutorials/Retrofit/article.html
使用jsonschema2pojo生成JSON數據的pojo類
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.