我刚刚开始使用android开发,我遇到了一个我无法解决的问题。
我使用Volley
在我的Android应用中调用了一个API,我得到以下响应:
[
{
"id": 25,
"user_id": 39,
"positionX": "51.4595484",
"positionY": "5.4757402",
"modified": "2016-12-15T00:00:00"
},
{
"id": 26,
"user_id": 40,
"positionX": "51.4595518",
"positionY": "5.4757409",
"modified": "2016-12-15T00:00:00"
},
{
"id": 27,
"user_id": 41,
"positionX": "51.459554",
"positionY": "5.4757413",
"modified": "2016-12-15T00:00:00"
},
{
"id": 28,
"user_id": 42,
"positionX": "51.459554",
"positionY": "5.4757413",
"modified": "2016-12-15T00:00:00"
}
]
我正在尝试从JSONArray
获取数据,但我无法使其正常工作......这是我的代码:
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
for (int i = 0; i < jsonObject.length(); i++) {
JSONObject row = jsonObject.getJSONObject();
points.add(new LatLng(row.getDouble("positionX"),row.getDouble("positionY")));
}
Toast.makeText(getApplicationContext(), "Updated users info." + points.get(0).toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
答案 0 :(得分:1)
您只需从row
而不是第一个JSONArray
对象获取JSON
,只需执行此操作
1。)创建JSONAray
2.。)使用索引
遍历数组并获取JSONObject
3.。)从第二步中检索到的JSONObject
中获取数据
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject row = jsonArray.getJSONObject(i);
points.add(new LatLng(row.getDouble("positionX"),row.getDouble("positionY")));
}
改进:为避免丢失密钥和值的异常,请使用optDouble来处理字符串形式的缺失值或值
答案 1 :(得分:0)
试试这个
@Override
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject row= jsonArray.getJSONObject(i)
points.add(new LatLng(row.getDouble("positionX"),row.getDouble("positionY")));
}
Toast.makeText(getApplicationContext(), "Updated users info." + points.get(0).toString(), Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "error" + e.getMessage(), Toast.LENGTH_LONG).show();
}
}
但我建议您使用 Gson Library 来解析json,这是最好的商业
下载 - http://www.java2s.com/Code/Jar/g/Downloadgson222jar.htm
如何添加lib- Android Studio: Add jar as library?
如何使用它 - https://blog.ajduke.in/2013/07/28/getting-started-with-google-gson/或https://sites.google.com/site/gson/gson-user-guide#TOC-Primitives-Examples