Transformers in Retrofit

After we receive the response from the server, both okHttp and Retrofit can only receive data of the String type. In actual development, we often need to parse the string and convert it into a Java Bean object. For example, if the server response data is a string in JSON format, then we can use the GSON library to complete the deserialization operation. And Retrofit provides multiple converters so that the response can complete automatic data conversion. The following uses json parsing as an example.


add converter dependency

implementation "com.squareup.retrofit2:converter-gson:2.9.0"


Step 1: Obtain Java Bean and generate entity class

Enter the wanandroid API open platform https://www.wanandroid.com/blog/show/2, use the login interface inside as 

https://www.wanandroid.com/user/login Method: POST Parameters: username, password

Use Postman to view the request result of this interface:


 

Enter the online JSON verification formatting tool (Be JSON) , select json to generate the java entity class, paste the returned result, and then change the name of class to BaseResponse, and Package is your package name 

Download the code and copy the downloaded file to the project directory

Generate the toString method in the code (both are required) click alt+insert and then click toString()

 

 


Step 2: Create a Java interface based on the Http interface

package com.example.networkdemo;

import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.POST;

public interface WanAndroidService {
    @POST("user/login")
    @FormUrlEncoded
    Call<BaseResponse> login(@Field("username") String username, @Field("password") String pwd);
}


Step 3: Use the converter, BaseResponse receives the return value

package com.example.networkdemo;

import org.junit.Test;
import java.io.IOException;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitTest {

    //使用转换器
    Retrofit retrofit2=new Retrofit
         .Builder()
         .baseUrl("https://www.wanandroid.com/")
         .addConverterFactory(GsonConverterFactory.create())//添加转换器
         .build();
    WanAndroidService wanAndroidService=retrofit2.create(WanAndroidService.class);


    @Test
    public void loginConvertTest() throws IOException {
        //登录
        Call<BaseResponse> call = wanAndroidService.login("dll", "dl666666");
        //发送请求将数据转换成java对象
        Response<BaseResponse> response = call.execute();
        BaseResponse baseResponse = response.body();
        System.out.println(baseResponse);

    }


}


operation result:

 The converter completes the automatic conversion

Guess you like

Origin blog.csdn.net/weixin_53443677/article/details/126402113