前言
在這一篇文章中颗搂,主要講一下如何使用Gson解釋服務(wù)器返回的具有固定格式的數(shù)據(jù)。
分析
服務(wù)器:在本地使用nodejs的express框架建立的簡單服務(wù)器疚察。它返回了的數(shù)據(jù)如下:
var testArrayStr = "{\"data\": [{\"cnName\": \"jakewharton\",\"age\": 13,\"IsBoy\": true}, {\"cnName\": \"小紅\",\"age\": 24,\"IsBoy\": false}],\"msg\": \"\",\"status\": 200}";
var testObjStr = "{\"data\": {\"cnName\": \"小紅\",\"age\": 24,\"IsBoy\": false},\"msg\": \"\",\"status\": 200}";
res.end(testObjStr);
我們可以和服務(wù)器約定返回的格式模版如下蒸走,他們的主要區(qū)別是data,可以是對象或者對象的數(shù)組形式貌嫡。
定義解釋data為對象的模板:
public class BaseObjectResult<T> {
public T data;
public String msg;
public int status;
}
定義解釋data為數(shù)組的模版:
public class BaseArrayResult<T> {
public List<T> data;
public String msg;
public int status;
}
實(shí)體對象:
TestData.java
public class TestData {
public String cnName;
public int age;
public boolean IsBoy;
@Override
public String toString() {
return "testData:" +
"cnName=" + this.cnName + " " +
"age=" + this.age + " " +
"IsBogy=" + this.IsBoy;
}
}
使用retrofit和gson解釋
自定義Converter.Factory
public class DecodeConverterFactory extends Converter.Factory {
public static DecodeConverterFactory create() {
return create(new Gson());
}
public static DecodeConverterFactory create(Gson gson) {
return new DecodeConverterFactory(gson);
}
private final Gson gson;
private DecodeConverterFactory(Gson gson) {
if (gson == null) throw new NullPointerException("gson == null");
this.gson = gson;
}
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new CustomResponseBodyConverter<>(adapter, type);
}
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
TypeAdapter<?> adapter = gson.getAdapter(TypeToken.get(type));
return new DecodeRequestBodyConverter<>(gson, adapter);
}
}
CustomResponseBodyConverter.java
public class CustomResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final TypeAdapter<T> adapter;
private Type mType;
public CustomResponseBodyConverter(TypeAdapter<T> adapter, Type type) {
this.adapter = adapter;
this.mType = type;
}
@Override
public T convert(ResponseBody value) throws IOException {
//解密字符串
if(mType == String.class) {
return (T) value.string();
} else {
}
}
}
DecodeRequestBodyConverter.java
public class DecodeRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");
private static final Charset UTF_8 = Charset.forName("UTF-8");
private final Gson gson;
private final TypeAdapter<T> adapter;
DecodeRequestBodyConverter(Gson gson,TypeAdapter<T> adapter){
this.gson = gson;
this.adapter = adapter;
}
@Override
public RequestBody convert(T value) throws IOException {
Buffer buffer = new Buffer(); //value.toString()
Writer writer = new OutputStreamWriter(buffer.outputStream(),UTF_8);
JsonWriter jsonWriter = gson.newJsonWriter(writer);
adapter.write(jsonWriter,value);
jsonWriter.flush();
return RequestBody.create(MEDIA_TYPE,buffer.readByteString());
}
}
開始使用:
TestDataApi.java
public interface TestDataApi {
@GET("/")
Call<BaseObjectResult<TestData>> getArrayData();
}
當(dāng)data為對象時(shí):
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.20.168:3000")
.addConverterFactory(DecodeConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
TestDataApi testDataApi = retrofit.create(TestDataApi.class);
Call<BaseObjectResult<TestData>> resultCall = testDataApi.getArrayData();
resultCall.enqueue(new Callback<BaseObjectResult<TestData>>() {
@Override
public void onResponse(Call<BaseObjectResult<TestData>> call, Response<BaseObjectResult<TestData>> response) {
if(response.isSuccessful()) {
if(response.body() != null) {
TestData testData = response.body().data;
Log.d("hyj", "msg=" + response.body().msg + " "
+ "status=" + response.body().status + " "
+ testData.toString());
}
}
}
@Override
public void onFailure(Call<BaseObjectResult<TestData>> call, Throwable t) {
ToastUtil.showShort(mContext, t.getMessage());
}
});
輸出的結(jié)果是:
04-08 16:04:56.053 31894-31894/com.zhangsunyucong.chanxa.testproject D/hyj: msg= status=200 testData:cnName=小紅 age=24 IsBogy=false
當(dāng)data為數(shù)組時(shí):
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("http://192.168.20.168:3000")
.addConverterFactory(DecodeConverterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
TestDataApi testDataApi = retrofit.create(TestDataApi.class);
Call<BaseArrayResult<TestData>> resultCall = testDataApi.getArrayData();
resultCall.enqueue(new Callback<BaseArrayResult<TestData>>() {
@Override
public void onResponse(Call<BaseArrayResult<TestData>> call, Response<BaseArrayResult<TestData>> response) {
if(response.isSuccessful()) {
if(response.body() != null) {
List<TestData> testData = response.body().data;
if(testData != null) {
for(int i = 0; i < testData.size(); i++) {
Log.d("hyj", "msg=" + response.body().msg + " "
+ "status=" + response.body().status + " "
+ testData.get(i).toString());
}
}
}
}
}
@Override
public void onFailure(Call<BaseArrayResult<TestData>> call, Throwable t) {
ToastUtil.showShort(mContext, t.getMessage());
}
});
輸出的結(jié)果是:
04-08 16:11:44.703 32440-32440/com.zhangsunyucong.chanxa.testproject D/hyj: msg= status=200 testData:cnName=jakewharton age=13 IsBogy=true
04-08 16:11:44.703 32440-32440/com.zhangsunyucong.chanxa.testproject D/hyj: msg= status=200 testData:cnName=小紅 age=24 IsBogy=false
手動(dòng)解釋####
關(guān)鍵的代碼是:
private ParameterizedType type(final Class raw, final Type... args) {
return new ParameterizedType() {
public Type getRawType() {
return raw;
}
public Type[] getActualTypeArguments() {
return args;
}
public Type getOwnerType() {
return null;
}
};
}
當(dāng)data返回的是對象時(shí):
TestDataApi testDataApi = retrofit.create(TestDataApi.class);
Call<String> resultCall = testDataApi.getArrayData();
resultCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()) {
if(response.body() != null) {
String testDataStr = response.body();
Gson gson = new Gson();
BaseObjectResult<TestData> testData = gson.fromJson(testDataStr,
type(BaseObjectResult.class, TestData.class));
Log.d("hyj", "msg=" + testData.msg + " "
+ "status=" + testData.status + " "
+ testData.data.toString());
}
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
ToastUtil.showShort(mContext, t.getMessage());
}
});
當(dāng)返回的data是數(shù)組時(shí):
TestDataApi testDataApi = retrofit.create(TestDataApi.class);
Call<String> resultCall = testDataApi.getArrayData();
resultCall.enqueue(new Callback<String>() {
@Override
public void onResponse(Call<String> call, Response<String> response) {
if(response.isSuccessful()) {
if(response.body() != null) {
String testDataStr = response.body();
Gson gson = new Gson();
BaseArrayResult<TestData> testData = gson.fromJson(testDataStr,
type(BaseArrayResult.class, TestData.class));
if(testData != null && testData.data != null) {
for(int i = 0; i < testData.data.size(); i++) {
Log.d("hyj", "msg=" + testData.msg + " "
+ "status=" + testData.status + " "
+ testData.data.get(i).toString());
}
}
}
}
}
@Override
public void onFailure(Call<String> call, Throwable t) {
ToastUtil.showShort(mContext, t.getMessage());
}
});
它們返回的結(jié)果和第一種方法的返回結(jié)果是一樣的比驻。