★43.Retrofit + Gson

2017-06-29  本文已影响0人  iDragonfly

简介

反序列化示例(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();
    }
});
上一篇 下一篇

猜你喜欢

热点阅读