这是我需要获取的ArrayList的示例,如何获取此Array?我使用凌空的GET方法来获取此数组并在Recycler View中显示。
[
{
"_id": "a2a1",
"name": "Flower",
"image": {
"_id": "a2a2",
"name": "flower.jpg",
"url": "/uploads/c8c8c.jpg",
"related": [
"a2a1"
],
"id": "0a2a2"
},
},
{
"_id": "433d",
"name": "Bouquet",
"id": "433d",
"image": {
"_id": "433e",
"name": "baloon.jpg",
"url": "/uploads/247db.jpg",
"related": [
"433d"
],
"id": "433e"
},
}]
这是我的代码,通过使用Volley的Get方法获取数组,我已经放置了正确的api,但是我没有获取数组的列表。
private void FlowerList(){
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
FlowerModel[] models = gson.fromJson(String.valueOf(json.getJSONArray(null)), FlowerModel[].class);
flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
答案 0 :(得分:0)
如果您使用的是Gson verson 2.8',则
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, TypeToken.getParameterized(ArrayList.class, FlowerModel.class).getType());
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
对于旧版本
try {
json = new JSONObject(response);
ArrayList<FlowerModel> models = gson.fromJson(response, new TypeToken<ArrayList<FlowerModel>>(){}.getType(););
//flowerAdapter.addBatch(Arrays.asList(models));
} catch (JSONException e) {
e.printStackTrace();
}
答案 1 :(得分:0)
尝试一下...。我已经修改了您的代码
ArrayList<String> stringArrayList;
String id1,name,id2;
StringRequest request = new StringRequest(
Request.Method.GET,
ServerApi.URL_FLOWER,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Gson gson = new GsonBuilder().create();
if(response != null) {
JSONObject json = null;
try {
json = new JSONObject(response);
JSONArray jsonArray=json.getJSONArray("Your_response_arrayName");
stringArrayList=new ArrayList<>();
for(i=0;i<jsonArray.length;i++){
JSONObject jsonObject=jsonArray.getJSONObject(i);
stringArrayList.add(jsonObject);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}
);
Volley.newRequestQueue(getContext()).add(request);
}
希望这会对您有所帮助