希望在Android开发者网站上使用该类,该网站使用Volley和Gson从url获取和反序列化json数据以解析为数组。我还是初学者,所以我试图实例化课程,但我不确定如何格式化参数。试图寻找实现,但他们似乎还使用其他API。返回的json只有一个字段和值,因此类对象clazz有一个字段。
public class GsonRequest<T> extends Request<T> {
private final Gson gson = new Gson();
private final Class<T> clazz;
private final Map<String, String> headers;
private final Listener<T> listener;
/**
* Make a GET request and return a parsed object from JSON.
*
* @param url URL of the request to make
* @param clazz Relevant class object, for Gson's reflection
* @param headers Map of request headers
*/
public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
Listener<T> listener, ErrorListener errorListener) {
super(Method.GET, url, errorListener);
this.clazz = clazz;
this.headers = headers;
this.listener = listener;
}
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
@Override
protected void deliverResponse(T response) {
listener.onResponse(response);
}
@Override
protected Response<T> parseNetworkResponse(NetworkResponse response) {
try {
String json = new String(
response.data,
HttpHeaderParser.parseCharset(response.headers));
return Response.success(
gson.fromJson(json, clazz),
HttpHeaderParser.parseCacheHeaders(response));
} catch (UnsupportedEncodingException e) {
return Response.error(new ParseError(e));
} catch (JsonSyntaxException e) {
return Response.error(new ParseError(e));
}
}
}
只是想让示例启动并运行所以它至少可以接收要在屏幕上显示的数据。
答案 0 :(得分:0)
首先,您需要根据预期的JSON响应定义模型类。
例如,如果您的JSON是用户数组,那么模型类将如下所示,
Users.Java
public class Users extends Object implements Serializable {
private static final long serialVersionUID = 1L;
@SerializedName("users")
private ArrayList<User> arrListUser;
public ArrayList<User> getArrListBusinessObj() {
return arrListUser;
}
public static class User extends Object implements Serializable
{
private static final long serialVersionUID = 1L;
private String user_id;
private String name;
private String artwork;
public String getBusinessObjId() {
return user_id;
}
public String getName() {
return name;
}
public String getArtwork() {
return artwork;
}
}
}
然后,在您收到网络响应的地方,请拨打以下方法:
Users users = (Users)gson.fromJson(data, Users.class); //data is string form response from server