Android Studio中如何通过Retrofit服务在请求中传递JSON数据
在Android Studio中用Retrofit传递JSON数据的方法
嘿,我来帮你搞定Retrofit传递JSON数据的问题,还有你提供的图片里那种特定请求的处理方式~
一、通用场景:整个请求体为JSON格式
这是最常见的情况,直接把JSON对象作为请求体发送,步骤如下:
- 配置依赖
首先确保你的build.gradle(Module level)里添加了Retrofit和Gson转换器的依赖(版本可以用最新的,这里给个常用版本参考):
implementation 'com.squareup.retrofit2:retrofit:2.9.0' implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
- 创建数据模型类
把你要传递的JSON结构转换成Java/Kotlin类,Gson会自动帮你做序列化和反序列化。比如要传这样的JSON:
{ "username": "demo_user", "password": "demo_pass" }
对应的Java类可以这么写:
public class LoginRequest { private String username; private String password; // 构造方法,方便快速创建对象 public LoginRequest(String username, String password) { this.username = username; this.password = password; } // 也可以添加getter/setter,根据需求来 }
如果JSON字段和类字段名不一样,记得用@SerializedName注解映射,比如@SerializedName("user_name") private String username;
- 定义Retrofit接口
用@POST标注接口方法,再用@Body注解传递模型对象,Retrofit会自动把对象转成JSON:
public interface ApiService { // 替换成你的实际接口endpoint @POST("user/login") Call<LoginResponse> login(@Body LoginRequest loginRequest); }
这里的LoginResponse是你服务器返回数据对应的模型类,按需创建即可。
- 初始化Retrofit并发起请求
// 初始化Retrofit实例 Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-server-base-url.com/") // 替换成你的服务器基础地址 .addConverterFactory(GsonConverterFactory.create()) // 添加Gson转换器 .build(); // 创建接口实例 ApiService apiService = retrofit.create(ApiService.class); // 构建请求对象并发起请求 LoginRequest request = new LoginRequest("demo_user", "demo_pass"); Call<LoginResponse> call = apiService.login(request); // 异步请求(推荐用异步,避免阻塞主线程) call.enqueue(new Callback<LoginResponse>() { @Override public void onResponse(Call<LoginResponse> call, Response<LoginResponse> response) { if (response.isSuccessful()) { // 请求成功,处理返回的数据 LoginResponse responseData = response.body(); } else { // 服务器返回错误码,处理错误 } } @Override public void onFailure(Call<LoginResponse> call, Throwable t) { // 网络请求失败,比如无网络、超时等 t.printStackTrace(); } });
二、针对你图片中的特定请求:表单参数嵌套JSON字符串
从你提供的图片来看,这个请求是以表单形式提交参数,其中一个参数(比如request)的值是JSON格式的字符串,这种情况处理方式略有不同:
方法1:手动将模型转为JSON字符串,用@Field传递
- 先添加字符串转换器的依赖(因为要处理JSON字符串):
implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
- 创建你要嵌套的JSON对应的模型类,比如:
public class CustomRequest { private String name; private int age; public CustomRequest(String name, int age) { this.name = name; this.age = age; } }
- 用Gson把模型转成JSON字符串:
Gson gson = new Gson(); CustomRequest customReq = new CustomRequest("张三", 28); String requestJsonStr = gson.toJson(customReq);
- 修改Retrofit接口,用
@FormUrlEncoded和@Field来定义表单请求:
public interface ApiService { @FormUrlEncoded @POST("your-specific-endpoint") // 替换成图片里的接口地址 Call<YourResponse> submitCustomRequest(@Field("request") String requestJsonStr); }
方法2:用@PartMap处理更复杂的表单场景
如果除了JSON参数,还有其他表单参数(比如token、timestamp),可以用@PartMap来灵活构建:
public interface ApiService { @Multipart @POST("your-specific-endpoint") Call<YourResponse> submitCustomRequest(@PartMap Map<String, RequestBody> params); }
然后构建请求参数:
// 把嵌套的JSON转成RequestBody Gson gson = new Gson(); String requestJson = gson.toJson(new CustomRequest("李四", 32)); RequestBody jsonRequestBody = RequestBody.create(requestJson, MediaType.parse("application/json")); // 构建参数Map Map<String, RequestBody> paramMap = new HashMap<>(); paramMap.put("request", jsonRequestBody); // 添加其他表单参数,比如token paramMap.put("token", RequestBody.create("your-auth-token", MediaType.parse("text/plain"))); // 发起请求 Call<YourResponse> call = apiService.submitCustomRequest(paramMap); call.enqueue(...); // 后续的回调处理和之前一样
内容的提问来源于stack exchange,提问作者Sandeep Sharma
相关产品推荐
相关产品推荐

