无法使用 GSON 识别我的 json 的特定数组。并将它们添加到列表中

Unable to identify the perticular array of of my json using GSON. and add them to a list

主要Activity代码片段...我试过responce.getObject但是没用...

JsonArrayRequest request = new JsonArrayRequest( Request.Method.GET,
               URL,
                null,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        if (response == null) {
                            Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                            return;
                        }
                        List<Person> persons = new Gson().fromJson(response.toString(), new TypeToken<List<Person>>() {
                        }.getType());

                        // adding persons to cart list
                        cartList.clear();
                        cartList.addAll(persons);

一个Json文件

{
  "code": 1200,
  "message": "Data Retrieved",
  "data": [
    {
      "id": 1,
      "name": "Vangipurapu Venkata Sai Laxman",
      "skills": "Cricketer, Batsman",
      "image": "https://qph.ec.quoracdn.net/main-qimg-4f5029c4319b41270f5643d461979645-c"
    },
    {
      "id": 2,
      "name": "Himesh Reshammiya",
      "skills": "music director, singer, producer, lyricist, distributor and actor",
      "image": "https://starsunfolded-1ygkv60km.netdna-ssl.com/wp-content/uploads/2016/01/Himesh-Reshammiya-nasal-singing.jpg"
    }
]
}

如何识别对象"data"并访问所有数组。

您需要解析整个 JSON 响应,而不仅仅是 "data" 属性。用于解析它的 GSON 文件可能看起来像这样:

public class MyJsonResponse {
    @SerializedName("code")
    private int code;
    @SerializedName("message")
    private String message;
    @SerializedName("data")
    private List<Person> data;
}

然后您可以从解析的响应中获取数据字段。

您可以使用 this link 将您的 json 响应转换为 POJO 类。 对于您当前的响应,它还实现了 Parcelable 下面是代码:

JsonResponse.java

public class JsonResponse implements Parcelable
{

@SerializedName("code")
@Expose
private Integer code;
@SerializedName("message")
@Expose
private String message;
@SerializedName("data")
@Expose
private List<Datum> data = null;
public final static Parcelable.Creator<JsonResponse> CREATOR = new Creator<JsonResponse>() {


@SuppressWarnings({
"unchecked"
})
public JsonResponse createFromParcel(Parcel in) {
return new JsonResponse(in);
}

public JsonResponse[] newArray(int size) {
return (new JsonResponse[size]);
}

}
;

protected JsonResponse(Parcel in) {
this.code = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.message = ((String) in.readValue((String.class.getClassLoader())));
in.readList(this.data, (com.heyoe_chat.model.Datum.class.getClassLoader()));
}

public JsonResponse() {
}

public Integer getCode() {
return code;
}

public void setCode(Integer code) {
this.code = code;
}

public String getMessage() {
return message;
}

public void setMessage(String message) {
this.message = message;
}

public List<Datum> getData() {
return data;
}

public void setData(List<Datum> data) {
this.data = data;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(code);
dest.writeValue(message);
dest.writeList(data);
}

public int describeContents() {
return 0;
}

}

Datum.java 对于数组中的对象。

public class Datum implements Parcelable
{

@SerializedName("id")
@Expose
private Integer id;
@SerializedName("name")
@Expose
private String name;
@SerializedName("skills")
@Expose
private String skills;
@SerializedName("image")
@Expose
private String image;
public final static Parcelable.Creator<Datum> CREATOR = new Creator<Datum>() {


@SuppressWarnings({
"unchecked"
})
public Datum createFromParcel(Parcel in) {
return new Datum(in);
}

public Datum[] newArray(int size) {
return (new Datum[size]);
}

}
;

protected Datum(Parcel in) {
this.id = ((Integer) in.readValue((Integer.class.getClassLoader())));
this.name = ((String) in.readValue((String.class.getClassLoader())));
this.skills = ((String) in.readValue((String.class.getClassLoader())));
this.image = ((String) in.readValue((String.class.getClassLoader())));
}

public Datum() {
}

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getSkills() {
return skills;
}

public void setSkills(String skills) {
this.skills = skills;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public void writeToParcel(Parcel dest, int flags) {
dest.writeValue(id);
dest.writeValue(name);
dest.writeValue(skills);
dest.writeValue(image);
}

public int describeContents() {
return 0;
}

}

首先你不能在这种情况下使用JsonArrayRequest。这是因为您的 Myjson 文件 在根目录中没有数组,而是 object.You 应该使用 JsonObjectRequest 相反。

你的代码应该是这样的:

JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                    }.getType());

                    // adding persons to cart list
                    cartList.clear();
                    cartList.add(persons);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
    });

记得改

 List<Person> persons = new Gson().fromJson(response.toString(), new TypeToken<List<Person>>() {
                    }.getType());

Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                }.getType());

这是因为与上述相同的原因:您得到的是 json 对象 而不是 json 数组.

现在,Gson 的工作方式是它需要 class 到 'map' 收到的 Json到。因此你必须创建一个class。查看您的 Json,这是 Person class.

的简单实现
public class Person {
private int code;
private String message;
private List<Data> data;

public int getCode() {
    return code;
}

public String getMessage() {
    return message;
}

public List<Data> getData() {
    return data;
}

public class Data {
    private int id;
    private String name;
    private String skills;
    private String image;

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public String getSkills() {
        return skills;
    }

    public String getImage() {
        return image;
    }
}}

这就是您访问数据数组及其对象的方式。

for (int i = 0; i < cartList.size(); i++) {
                        for (Person.Data data : cartList.get(i).getData()) {
                            Log.d("TAG", "Name: " + data.getName() + ", Skill: " + data.getSkills() + ", Image: " + data.getImage() + ", id: " + data.getId());
                        }
                    }

这里我正在打印Logcat中的数据。确保在 onResponse() 块中执行此操作。

完整代码如下所示:

        requestQueue = Volley.newRequestQueue(this);
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET,
            URL,
            null,
            new Response.Listener<JSONObject>() {
                @Override
                public void onResponse(JSONObject response) {
                    if (response == null) {
                        Toast.makeText(getApplicationContext(), "Couldn't fetch the menu! Pleas try again.", Toast.LENGTH_LONG).show();
                        return;
                    }
                    Person persons = new Gson().fromJson(response.toString(), new TypeToken<Person>() {
                    }.getType());

                    // adding persons to cart list
                    cartList.clear();
                    cartList.add(persons);

                    for (int i = 0; i < cartList.size(); i++) {
                        for (Person.Data data : cartList.get(i).getData()) {
                            Log.d("TAG", "Name: " + data.getName() + ", Skill: " + data.getSkills() + ", Image: " + data.getImage() + ", id: " + data.getId());
                        }
                    }
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Log.d("error", error.toString());
                }
    });

    requestQueue.add(request);

希望对您有所帮助。