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

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 ();
}

@Override
public Converter<ResponseBody, ?> responseBodyConverter(Type type, Annotation[] annotations, Retrofit retrofit) {
    return new JsonResponseBodyConverter<JSONObject>();
}

@Override
public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值