要使用Retrofit和JSONObject解析JSON POST请求体,需要以下步骤:
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
public interface ApiService {
    @POST("your-endpoint")
    Call postData(@Body RequestBody requestBody);
}
 public class ApiClient {
    private static final String BASE_URL = "https://api.example.com/";
    private static Retrofit retrofit;
    public static Retrofit getClient() {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create())
                    .build();
        }
        return retrofit;
    }
}
JSONObject json = new JSONObject();
try {
    json.put("key1", "value1");
    json.put("key2", "value2");
} catch (JSONException e) {
    e.printStackTrace();
}
RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"), json.toString());
ApiService apiService = ApiClient.getClient().create(ApiService.class);
Call call = apiService.postData(requestBody);
call.enqueue(new Callback() {
    @Override
    public void onResponse(Call call, Response response) {
        if (response.isSuccessful()) {
            try {
                String jsonResponse = response.body().string();
                JSONObject jsonObject = new JSONObject(jsonResponse);
                // 在这里处理JSON响应
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
        } else {
            // 处理错误情况
        }
    }
    @Override
    public void onFailure(Call call, Throwable t) {
        t.printStackTrace();
        // 处理失败情况
    }
});
     这样,您就可以使用Retrofit和JSONObject解析JSON POST请求体了。请注意,上述代码只是一个示例,您需要根据您的API端点和JSON结构进行适当的更改。
                    上一篇:帮助使用pip和setx
                
下一篇:帮助使用SQL的SUM()函数?