我使用HttpURLConnection
来发布请求后跟响应:
请求后回复:
{
"LatestData": [{
"ExtraData": null,
"ID": 0,
"season": false,
"latest": 0,
"url": "http://www.awebsite.com/images/12.jpg"
}]
}
如何获取网址的价值?我试过跟随,但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();
}
}
}
答案 0 :(得分:2)
您需要将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();
}
答案 1 :(得分:1)
try {
JSONObject jsonObject = new JSONObject(sb);
String url = jsonObject.optJSONArray("LatestData").getJSONObject(0).optString("url");
} catch (JSONException e) {
e.printStackTrace();
}
答案 2 :(得分:0)
你的方法应该是这样的。
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();
}
答案 3 :(得分:0)
使用loadJSONArray
String url = loadJSONArray(sb)..getJSONObject(0).getString("url");
答案 4 :(得分:0)
你可以试试这个:
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
答案 5 :(得分:0)
使用jsonschema2pojo为JSON数据生成pojo类