Skip to content

Commit

Permalink
[add][what]增加一个泛型的序列化Callback (sample项目中有一个Json序列化的例子)
Browse files Browse the repository at this point in the history
[why]避免每种类型的返回对象都需要新建相对应的Callback类
  • Loading branch information
江佳铨 committed Jun 23, 2016
1 parent a209026 commit 1d717d1
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package com.zhy.http.okhttp.callback;

import java.io.IOException;
import java.lang.reflect.ParameterizedType;

import okhttp3.Response;

/**
* Created by JimGong on 2016/6/23.
*/

public abstract class GenericsCallback<T> extends Callback<T> {
IGenericsSerializator mGenericsSerializator;

public GenericsCallback(IGenericsSerializator serializator) {
mGenericsSerializator = serializator;
}

@Override
public T parseNetworkResponse(Response response, int id) throws IOException {
String string = response.body().string();
Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
if (entityClass == String.class) {
return (T) string;
}
T bean = mGenericsSerializator.transform(string, entityClass);
return bean;
}

}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.zhy.http.okhttp.callback;

/**
* Created by JimGong on 2016/6/23.
*/
public interface IGenericsSerializator {
<T> T transform(String response, Class<T> classOfT);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package com.zhy.sample_okhttp;

import com.google.gson.Gson;
import com.zhy.http.okhttp.callback.IGenericsSerializator;

/**
* Created by JimGong on 2016/6/23.
*/
public class JsonGenericsSerializator implements IGenericsSerializator {
Gson mGson = new Gson();
@Override
public <T> T transform(String response, Class<T> classOfT) {
return mGson.fromJson(response, classOfT);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.BitmapCallback;
import com.zhy.http.okhttp.callback.FileCallBack;
import com.zhy.http.okhttp.callback.GenericsCallback;
import com.zhy.http.okhttp.callback.StringCallback;
import com.zhy.http.okhttp.cookie.CookieJarImpl;

Expand Down Expand Up @@ -156,7 +157,7 @@ public void getUser(View view)
.addParams("username", "hyman")//
.addParams("password", "123")//
.build()//
.execute(new UserCallback()
.execute(new GenericsCallback<User>(new JsonGenericsSerializator())
{
@Override
public void onError(Call call, Exception e, int id)
Expand Down

0 comments on commit 1d717d1

Please sign in to comment.