再封裝Rx數據預和異常預處理的時候,由於為了簡便性,我的DataModel欄位會包含一些Json字元串沒有的欄位,這樣就導致了JSON解析報錯。大概錯誤就是:

還搞得內存溢出了喲!如果去網上查相關問題不一定有這個答案。或許某些問題可以找到。 後來跟網友討論下,當時說如果是缺少欄位可以,但是如果新增了欄位而Json字元串有沒有該欄位就不行。

然後我果斷就替換為了阿里的FastJson,FastJson內部做了類似的處理,所以沒有問題。簡單記錄下,後面看看實體類是否還可以進行二次封裝,盡量都可以用。

FastJson自定義解析器如下三個文件:

FastJsonConverterFactory.java

import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Converter;
import retrofit2.Retrofit;

public class FastJsonConverterFactory extends Converter.Factory{

public static FastJsonConverterFactory create() {
return new FastJsonConverterFactory();
}

/**
* 需要重寫父類中responseBodyConverter,該方法用來轉換伺服器返回數據
*/
@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
return new FastJsonResponseBodyConverter<>(type);
}

/**
* 需要重寫父類中responseBodyConverter,該方法用來轉換髮送給伺服器的數據
*/
@Override
public Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations, Retrofit retrofit) {
return new FastJsonRequestBodyConverter<>();
}
}

FastJsonResponseBodyConverter.java

import com.alibaba.fastjson.JSON;

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

import okhttp3.ResponseBody;
import okio.BufferedSource;
import okio.Okio;
import retrofit2.Converter;

public class FastJsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
private final Type type;

public FastJsonResponseBodyConverter(Type type) {
this.type = type;
}

/*
* 轉換方法
*/
@Override
public T convert(ResponseBody value) throws IOException {
BufferedSource bufferedSource = Okio.buffer(value.source());
String tempStr = bufferedSource.readUtf8();
bufferedSource.close();
return JSON.parseObject(tempStr, type);
}
}

FastJsonRequestBodyConverter.java

import com.alibaba.fastjson.JSON;

import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Converter;

public class FastJsonRequestBodyConverter<T> implements Converter<T, RequestBody> {
private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");

@Override
public RequestBody convert(T value) throws IOException {
return RequestBody.create(MEDIA_TYPE, JSON.toJSONBytes(value));
}
}

使用就簡單:

基本就可以了。測試了也沒有問題...其實有時候我們的同一個介面根據參數值不同可能結果會不同,所以基本上我們還是定義一個datamodel比較方便,如果定義多個的話,還得自己去處理JSON數據,感覺更麻煩了。所以目前小白看還是這種比較方便。

推薦閱讀:

查看原文 >>
相关文章