Android:Gson请求一个类对象数组

时间:2015-05-26 03:51:29

标签: android gson

我试图回想一下如何做到这一点。 我想发一个gson请求,并在其回复中有对象列表。我错过了关键的一步。我想我错过了对象的映射.. 由于我只是准备代码示例,我现在只使用imgur api。

以下是https://api.imgur.com/3/gallery/random/random/0

的有效负载
{"data":[{"id":"TJKugtd","title":"My brother's a little bitch, my mom agrees","description":null,"datetime":1362021619,"type":"image\/jpeg","animated":false,"width":766,"height":1024,"size":217570,"views":803505,"bandwidth":174818582850,"vote":null,"favorite":false,"nsfw":false,"section":"funny","account_url":null,"account_id":null,"comment_preview":null,"topic":null,"topic_id":0,"link":"http:\/\/i.imgur.com\/TJKugtd.jpg","comment_count":132,"ups":2728,"downs":54,"score":3393,"is_album":false},{"id":"MSoYTyY","title":"Wilbur and Tom","description":null,"datetime":1359986890,"type":"image\/jpeg","animated":false,"width":720,"height":540,"size":78934,"views":246569,"bandwidth":19462677446,"vote":null,"favorite":false,"nsfw":false,"section":"aww","account_url":"bohgues","account_id":597261,"comment_preview":null,"topic":null,"topic_id":0,"link":"http:\/\/i.imgur.com\/MSoYTyY.jpg","comment_count":30,"ups":893,"downs":24,"score":1373,"is_album":false},{"id":"wKT3W","title":"Look at this guy...","description":null,"datetime":1314720905,"type":"image\/jpeg","animated":false,"width":572,"height":473,"size":42159,"views":290237,"bandwidth":12236101683,"vote":null,"favorite":false,"nsfw":false,"section":"pics","account_url":null,"account_id":null,"comment_preview":null,"topic":null,"topic_id":0,"link":"http:\/\/i.imgur.com\/wKT3W.jpg","comment_count":85,"ups":636,"downs":51,"score":730,"is_album":false},{"id":"TDHJz","title":"\"You can never take a good picture of him\", his owners said to me.  Challenge accepted.","description":null,"datetime":1353566974,"type":"image\/jpeg","animated":false,"width":540,"height":720,"size":31549,"views":495090,"bandwidth":15619594410,"vote":null,"favorite":false,"nsfw":false,"section":"aww","account_url":"beee86","account_id":290426,"comment_preview":null,"topic":null,"topic_id":0,"link":"http:\/\/i.imgur.com\/TDHJz.jpg","comment_count":64,"ups":1829,"downs":33,"score":2364,"is_album":false},{"id":"ct4iT","title":"My grandparents, April 1956","description":null,"datetime":1351352985,"type":"image\/jpeg","animated":false,"width":3928,"height":2642,"size":541045,"views":474829,"bandwidth":256903856305,"vote":null,"favorite":false,"nsfw":false,"section":"pics","account_url":"alekanakalea","account_id":994367,"comment_preview":null,"topic":null,"topic_id":0,"link":"http:\/\/i.imgur.com\/ct4iT.jpg","comment_count":83,"ups":1030,"downs":20,"score":1548,"is_album":false},

由于字符串限制而缩短

实际通话

import android.content.Context;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.Volley;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;


public class GetImgurTask {

final static String TAG = "GetImgurTask";

public void getImgurTask(Context context) {
    RequestQueue queue = Volley.newRequestQueue(context);
    try {
        GsonRequest<Images> request = new GsonRequest<Images>(utils.urlEndpoint, Images.class, getHeaders(), getResponceListener(),getErrorListener());
        queue.add(request);

    } catch (AuthFailureError authFailureError) {
        authFailureError.printStackTrace();
    }

}
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String, String> headers = new HashMap<String,String>();
    headers.put("Authorization", "Client-ID " + utils.clientId);
    return headers;
}

private Response.Listener getResponceListener(){
    return new Response.Listener<Images[]>() {
        @Override
        public void onResponse(final Images[] response) {
            Log.d(TAG, "got a reply!");
        }
    };
}

private Response.ErrorListener getErrorListener() {

    return new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e("ERROR", error.toString());
        }
    };
}

}

Generic gson stuff

import com.android.volley.AuthFailureError;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.toolbox.HttpHeaderParser;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.Map;

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 Response.Listener<T> listener;

public GsonRequest(String url, Class<T> clazz, Map<String, String> headers,
                   Response.Listener<T> listener, Response.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 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));
    }
}

@Override
protected void deliverResponse(T response) {
    listener.onResponse(response);
}
}

包装

public class Images {
long id;
String title;
String description;
long datetime;
String type;
boolean animated;
int width;
int height;
long size;
long views;
long bandwidth;
boolean favorite;
boolean nsfw;
String section;
String account_url;
long account_id;
//    comment_preview: null
//    topic: null
int topic_id;
String link;
long comment_count;
long ups;
long downs;
long score;
boolean is_album;

public String getTitle() {
    return title;
}

public String getDescription() {
    return description;
}

public long getDatetime() {
    return datetime;
}

public String getType() {
    return type;
}

public boolean isAnimated() {
    return animated;
}

public int getWidth() {
    return width;
}

public int getHeight() {
    return height;
}

public long getSize() {
    return size;
}

public long getViews() {
    return views;
}

public long getBandwidth() {
    return bandwidth;
}

public boolean isFavorite() {
    return favorite;
}

public boolean isNsfw() {
    return nsfw;
}

public String getSection() {
    return section;
}

public String getAccount_url() {
    return account_url;
}

public long getAccount_id() {
    return account_id;
}

public int getTopic_id() {
    return topic_id;
}

public String getLink() {
    return link;
}

public long getComment_count() {
    return comment_count;
}

public long getUps() {
    return ups;
}

public long getDowns() {
    return downs;
}

public long getScore() {
    return score;
}

public boolean is_album() {
    return is_album;
}

//    vote: null

public long getId() {
    return id;
}

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


}

编辑:我认为错误在

return Response.success(gson.fromJson(json, clazz),
                HttpHeaderParser.parseCacheHeaders(response));

0 个答案:

没有答案