★43.Retrofit + Gson

简介

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

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

1. 定义Model

public interface BlogService {
    @GET("blog/{id}")
    Call<Blog> 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<Blog> call = service.getBlog(2);

6. 执行Call

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

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

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

1. 定义Model

public interface BlogService {
    @POST("blog")
    Call<Blog> 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<Blog> call = service.createBlog(blog);

6. 执行Call

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

    @Override
    public void onFailure(Call<Blog> call, Throwable t) {
        t.printStackTrace();
    }
});
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,001评论 19 139
  • 相信很多人都在使用Retrofit,我也在用,但是对它的理解都不是太深刻,现在Retrofit2已经出来一段时间,...
    WHOKNOWME阅读 7,555评论 6 19
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,637评论 25 708
  • 我早上给她发了个早,但是她没回,刚才我看了一下微信,她的微信步数只有16但是有个人已经点赞了,微信步数是从多到少排...
    爱她的我阅读 131评论 0 0
  • 1、今天上班任务不多,很快做完,现在需要反思这一个月的工作。效率提升的太慢,还是自己对代码熟悉程度不高,空闲时间多...
    任雨点阅读 104评论 0 0