从API获取2d数组时,正在解析响应。但是我无法获得这些值。
这就是得到回复的方式,
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
String api_uri = "http://192.168.0.106/api/something/";
HttpGet httpget = new HttpGet(api_uri);
httpget.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httpget);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
result = sb.toString();
Log.e("rAct", result);
} catch (Exception e) {
// Oops
Log.e("rActEr", e.toString());
} finally {
try {
if (inputStream != null) inputStream.close();
} catch (Exception squish) {}
}
result
字符串如下,
[
[
{
"id": 138,
"name": "asdasd",
"person_image": "http://something.in:9090/photos/14/1575.jpg",
"person_description": "bla bla blaa",
"bla_id": 1,
"blabal_id": 2,
"other_id": 7,
"category": "asd"
}
],
[
{
"id": 257,
"name": "asdasd",
"person_image": "http://something.in/asd.jpg",
"person_description": "asasdsad",
"bla_id": 1,
"blabal_id": 2,
"other_id": 7,
"category": "ASSSD"
}
]
]
所以现在我试图读取数据,
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
Log.e("testt", jsonobject.toString());
...
...
}
}catch....
无法从该jsonobject
获取任何信息
如何从结果中获取name
,person_image
,person_description
数据。
我试图让它们像jsonobject.optString("name")
一样,但一无所获。
使用一维数组,我得到了响应,并且可以按照上面相同的方式读取数据。
我需要修改什么才能读取所需的数据?
答案 0 :(得分:2)
当您拥有数组数组时,尝试读取外部数组内部的 json数组而不是 object :
try {
jsonarray = new JSONArray(result);
for (int i = 0; i < jsonarray.length(); i++) {
jsonarrayInner = jsonarray.getJSONArray(i);
//you can do one more loop here
for (int i = 0; i < jsonarrayInner.length(); i++) {
jsonobject = jsonarrayInner.getJSONObject(i);
Log.e("testt", jsonobject.toString());
}
...
...
}
}catch....
答案 1 :(得分:1)
在这种情况下,我更喜欢将Gson与 POJO 一起使用,它将json数组包装到java.util.List of <YourPojo>
List<MyPojo> myPojoList= new Gson().fromJson(jsonArray.toString(), new TypeToken<List<MyPojo>>() {
}.getType());
您的pojo应该与您的json属性匹配
所以您的课程应该是这样的
class MyPojo{
private id;
private String name ;
private String person_image;
private String person_description;
private int bla_id;
private int blabal_id;
private int other_id;
private String category;
}
通过这种方式,您将直接将json数组绑定到java对象