Retrofit2.0 converterfactory

首先贴出dependencies :

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:24.1.0'
    //google-gson
    compile 'com.google.code.gson:gson:2.7'
    //retrofit
    compile 'com.squareup.retrofit2:retrofit:2.1.0'
    //retrofit-string
    compile 'com.squareup.retrofit2:converter-scalars:2.1.0'
    //retrofit-converter-gson
    compile 'com.squareup.retrofit2:converter-gson:2.1.0'
    //retrofit-rxJava-converter
    compile 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    //rxjava
    compile 'io.reactivex:rxandroid:1.1.0'
    compile 'io.reactivex:rxjava:1.1.0'
}

新建一个Retrofit对象;

Retrofit retrofit = new Retrofit.Builder() .baseUrl(API).build();

添加类型转换的工厂类:
支持string类型
.addConverterFactory(ScalarsConverterFactory.create())

支持gson格式

.addConverterFactory(GsonConverterFactory.create(customGsonInstance))

支持observable类型

.addCallAdapterFactory(RxJavaCallAdapterFactory.create())

整体代码为:

Retrofit retrofit = new Retrofit
.Builder()
.baseUrl(API)                    
.addConverterFactory(ScalarsConverterFactory.create())                   .addConverterFactory(GsonConverterFactory.create(customGsonInstance))                        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                        .build();

其中的 customGsonInstance是返回的string要转换成gson对象;
上代码

final Gson customGsonInstance = new GsonBuilder()
                .registerTypeAdapter(GitModel.class,
                        new MarvelResultsDeserializer())
                .create();
class MarvelResultsDeserializer<T> implements JsonDeserializer<GitModel> {
        @Override
        public GitModel deserialize(JsonElement je, Type typeOfT,
                                   JsonDeserializationContext context) throws JsonParseException {
            // 转换Json的数据, 获取内部有用的信息
            //JsonElement results = je.getAsJsonObject();
            return new Gson().fromJson(je, typeOfT);
        }
    }

作用是把gson 格式的文件最终转化为GitModel的对象;

这里要提一下,这个GitModel 是通过GsonFormat插件来生成的,很方便,需要的请自行百度;

最终转化的结果要和自定义的interface相符合;

public interface GitApi {

    @GET("/users/{user}")      // here is the other url part.best way is to start using /
    Observable getFeed(@Path("user") String user);
    // string user is for passing values from edittext for eg: user=basil2style,google
    // response is the response from the server which is now in the POJO
}

其他的convert 依赖

•Gson: com.squareup.retrofit2:converter-gson
•Jackson: com.squareup.retrofit2:converter-jackson
•Moshi: com.squareup.retrofit2:converter-moshi
•Protobuf: com.squareup.retrofit2:converter-protobuf
•Wire: com.squareup.retrofit2:converter-wire
•Simple XML: com.squareup.retrofit2:converter-simplexml
•Scalars (primitives, boxed, and String): com.squareup.retrofit2:converter-scalars

Github代码

你可能感兴趣的:(android)