★43.Retrofit + Gson

简介

  • Gson Converter官网。
  • 注意到 Retrofit 所有的接口定义都是返回Call,但是其实可以是别的类型,比如Call,这需要相应的Converter

反序列化示例(Json字符串->Model对象)

1. 定义Model

public interface BlogService {
    @GET("blog/{id}")
    Call getFirstBlog(@Path("id") int id);
}

2. 创建Gson

Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd hh:mm:ss")
        .create();

3. 创建Retrofit

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://localhost:4567/")
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

4. 创建Model

BlogService service = retrofit.create(BlogService.class);

5. 创建Call

Call call = service.getBlog(2);

6. 执行Call

call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        // 已经转换为想要的类型了
        Blog result = response.body();
        System.out.println(result);
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        t.printStackTrace();
    }
});

序列化示例(Model对象->Json字符串)

1. 定义Model

public interface BlogService {
    @POST("blog")
    Call createBlog(@Body Blog blog);
}

2. 构建Gson

Gson gson = new GsonBuilder()
        .setDateFormat("yyyy-MM-dd hh:mm:ss")
        .create();

3. 构建Retrofit

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("http://localhost:4567/")
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

4. 创建Model

BlogService service = retrofit.create(BlogService.class);

5. 创建Call

Blog blog = new Blog();
blog.content = "新建的Blog";
blog.title = "测试";
blog.author = "name";
Call call = service.createBlog(blog);

6. 执行Call

call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        // 已经转换为想要的类型了
        Blog result = response.body();
        System.out.println(result);
    }

    @Override
    public void onFailure(Call call, Throwable t) {
        t.printStackTrace();
    }
});

你可能感兴趣的:(★43.Retrofit + Gson)