Retrofit2.0解析时使用json而不使用Gson

来源:互联网 发布:淘宝c店的类目 保证金 编辑:程序博客网 时间:2024/06/04 20:10

Retrofit2.0解析时使用json而不使用Gson

在开发过程中,难免会遇到一些后台接口写的不规范的json,使用Retrofit2.0的就不好使用Gson解析了,只能用json。
然而Retrofit2.0没有提供json解析器,因此这里有两种方法来使用。
如果不规范的Json就不好使用Gson如下:

{
“success”: true,
“result”: {
“1”: [
{
“serviceState”: “1”,
“serviceNumber”: “1101”
},
{
“serviceState”: “”,
“serviceNumber”: “1105”
}
],
“2”: [
{
“serviceState”: “1”,
“price”: “8.00”
}
],
“3”: [
{
“serviceState”: “”,
“price”: “5.00”
}
],
“4”: [
{
“serviceState”: “1”,
“price”: “0.00”
}
]
}
}


retrofit2.0在android studio中的引入
compile ‘com.squareup.retrofit2:retrofit:2.0.1’
compile ‘com.squareup.retrofit2:retrofit:2.0.1’
compile ‘com.squareup.retrofit2:adapter-rxjava:2.0.1’
compile ‘com.squareup.retrofit2:converter-gson:2.0.1’
compile ‘com.squareup.okhttp3:logging-interceptor:3.1.2’

方法一:

使用使用okhttp3里的ResponseBody

public class RestPool {    public ApiService init() {        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();        // log拦截器  打印所有的log        logging.setLevel(HttpLoggingInterceptor.Level.BODY);        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(logging)                .addInterceptor(new TokenInterceptor())                .build();        Gson gson = new GsonBuilder()                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")                .create();        Retrofit retrofit = new Retrofit.Builder()                .client(client)                .baseUrl(Constant.PAY_URL)                .addConverterFactory(GsonConverterFactory.create(gson))                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())                .build();        ApiService service = retrofit.create(ApiService.class);        return serv public interface ApiService {    @POST("tradeAction!queryValueAddedServices.action")    Call<ResponseBody> myBusiness(@Query("token") String token); }  

new RestPool().init().myBusiness(token).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
String resultBody;
try {
resultBody = new String(response.body().bytes());
JSONObject jsonObject = new JSONObject(resultBody);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onFailure(Call call, Throwable t) {
}
});

方法二:

自己写个转化器:

public class JsonConverterFactory extends Converter.Factory {

public static JsonConverterFactory create() {    return new JsonConverterFactory ();}@Overridepublic Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {    return new JsonResponseBodyConverter<JSONObject>();}@Overridepublic Converter<?, RequestBody> requestBodyConverter(Type type, Annotation[] parameterAnnotations, Annotation[] methodAnnotations,Retrofit retrofit) {    return new JsonRequestBodyConverter<JSONObject>();} }
final class JsonRequestBodyConverter<T> implements Converter<T, RequestBody> {    private static final MediaType MEDIA_TYPE = MediaType.parse("application/json; charset=UTF-8");    JsonRequestBodyConverter() {    }    public RequestBody convert(T value) throws IOException {        return RequestBody.create(MEDIA_TYPE, value.toString());    }}final class JsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {    JsonResponseBodyConverter() {    }    @Override    public T convert(ResponseBody value) throws IOException {        JSONObject jsonObj;        try {            jsonObj = new JSONObject(value.string());            return (T) jsonObj;        } catch(JSONException e) {            return null;        }    }}public class BusRestPool {    public ApiService init() {        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();        // log拦截器  打印所有的log        logging.setLevel(HttpLoggingInterceptor.Level.BODY);        OkHttpClient client = new OkHttpClient.Builder()                .addInterceptor(logging)                .addInterceptor(new TokenInterceptor())                .build();        Gson gson = new GsonBuilder()                .setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ")                .create();        Retrofit retrofit = new Retrofit.Builder()                .client(client)                .baseUrl(Constant.PAY_URL)                .addConverterFactory(JsonConverterFactory.create())                .build();        ApiService service = retrofit.create(ApiService.class);        return service;    }}     /**     *查询业务     */    @POST("tradeAction!queryValueAddedServices.action")    Call<JSONObject> myBusiness(@Query("token") String token);     

private void ss(){
new BusRestPool().init().myBusiness(“token”).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) {
JSONObject jsonObject = response.body();
}

        @Override        public void onFailure(Call<JSONObject> call, Throwable t) {        }    });}

“`
这两种方法都可以,但是第一种方法简单些。

0 0
原创粉丝点击