First create Models:
public class CategoryModel
{
public String blah;
}
public class PostModel
{
public int id;
public String type;
public String slug;
public String url;
public String status;
public String title;
public String title_plain;
public String content;
public String modified;
public List<CategoryModel> categories;
}
public class PostsModel
{
public String status;
public int count;
public int count_total;
public int pages;
public List<PostModel> posts;
}
then use gson;
in gradle:
compile 'com.google.code.gson:gson:2.4'
then in code get your object:
JSONObject json;
Gson gson = new Gson();
try {
json = new JSONObject(yourJsonString)
PostsModel result = gson.fromJson(json, PostsModel.class);
return result; // this is your deserialized response object
}catch(Exception e){
}
Volley:
in app class:
private VolleyServiceSingleton mVolleySingleton;
private RequestQueue mVolleyApiClient;
on create:
mVolleySingleton = VolleyServiceSingleton.getInstance();
mVolleyApiClient = mVolleySingleton.gerRequestQueue();
String request:
class VolleyStringRequest extends StringRequest
{
private Map<String, String> mParams;
public VolleyStringRequest(int method, String url, Response.Listener<String> listener, Response.ErrorListener errorListener, Map<String, String> requestParams) {
super(method, url, listener, errorListener);
mParams = requestParams;
afterRequestErrorRunnable = null;
Log.e("Request",url);
}
@Override
protected VolleyError parseNetworkError(VolleyError volleyError) {
if(volleyError.networkResponse != null && volleyError.networkResponse.data != null){
try {
Log.e("errorResponse", new String( volleyError.networkResponse.data, "utf-8" ));
}catch(Exception e){
}
}
return super.parseNetworkError(volleyError);
}
@Override
public RetryPolicy getRetryPolicy() {
DefaultRetryPolicy retryPolicy = new DefaultRetryPolicy(
TIMEOUT_IN_MILLISECONDS,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT);
return retryPolicy;
}
@Override
public Map getHeaders() throws AuthFailureError {
Map headers = new HashMap();
headers.put("Accept-Charset","utf-8");
//headers.put("Accept", RITEAID_HTTP_CONTENT_TYPE);
return headers;
}
@Override
public Map<String, String> getParams() {
return mParams;
}
}
and request (this must be customized):
HashMap<String, String> paramMap = new HashMap<String, String>();
paramMap.put("sign_in_username_email", Utils.nullToStringOrString(username));
paramMap.put("sign_in_password", password != null ? Utils.passwordConvert(password) : "");
paramMap.put("key", Constants.API_KEY);
mResponseHandler = getResponseHandler(requestUrl, positiveResponseFunc, inClass);
VolleyStringRequest request = new VolleyStringRequest(Request.Method.POST, getFinalUrl(requestUrl, null), getResponseHandler(requestUrl, positiveResponseFunc, inClass), createErrorListener(context, progress), paramMap);
request.setRetryPolicy(mRetryPolicy);
request.setTag(REQUEST_TAG);
mVolleyApiClient.add(request);