且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在不使用 GSON 或 android 中的任何其他库的情况下使用改造获得字符串响应

更新时间:2022-11-03 21:00:37

** 更新 ** 标量转换器已添加到改造中,允许 String 响应比我的原始答案更简洁下面.

** Update ** A scalars converter has been added to retrofit that allows for a String response with less ceremony than my original answer below.

示例界面——

public interface GitHubService {
    @GET("/users/{user}")
    Call<String> listRepos(@Path("user") String user);
}

ScalarsConverterFactory 添加到您的改造构建器.注意:如果使用ScalarsConverterFactory和另一个工厂,先添加标量工厂.

Add the ScalarsConverterFactory to your retrofit builder. Note: If using ScalarsConverterFactory and another factory, add the scalars factory first.

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl(BASE_URL)
    .addConverterFactory(ScalarsConverterFactory.create())
    // add other factories here, if needed.
    .build();

您还需要在 gradle 文件中包含标量转换器 --

You will also need to include the scalars converter in your gradle file --

implementation 'com.squareup.retrofit2:converter-scalars:2.1.0'

--- 原始答案(仍然有效,只是更多的代码)---

--- Original Answer (still works, just more code) ---

我同意@CommonsWare 的观点,您想拦截请求以自己处理 JSON 似乎有点奇怪.大多数情况下,POJO 拥有您需要的所有数据,因此无需在 JSONObject 领域中乱搞.我怀疑使用自定义 gson TypeAdapter 或改造 Converter 如果您需要操作 JSON.然而,改造提供了更多通过 Gson 进行的 JSON 解析.它还管理 REST 请求中涉及的许多其他繁琐任务.仅仅因为您不想使用其中一项功能,并不意味着您必须将整个功能都扔掉.有时您只想获取原始流,所以这里是如何做到的 -

I agree with @CommonsWare that it seems a bit odd that you want to intercept the request to process the JSON yourself. Most of the time the POJO has all the data you need, so no need to mess around in JSONObject land. I suspect your specific problem might be better solved using a custom gson TypeAdapter or a retrofit Converter if you need to manipulate the JSON. However, retrofit provides more the just JSON parsing via Gson. It also manages a lot of the other tedious tasks involved in REST requests. Just because you don't want to use one of the features, doesn't mean you have to throw the whole thing out. There are times you just want to get the raw stream, so here is how to do it -

首先,如果您使用的是 Retrofit 2,您应该开始使用 Call API.使用 okhttp 中的 ResponseBody --

First, if you are using Retrofit 2, you should start using the Call API. Instead of sending an object to convert as the type parameter, use ResponseBody from okhttp --

public interface GitHubService {
    @GET("/users/{user}")
    Call<ResponseBody> listRepos(@Path("user") String user);
}

然后你就可以创建并执行你的调用 --

then you can create and execute your call --

GitHubService service = retrofit.create(GitHubService.class);
Call<ResponseBody> result = service.listRepos(username);
result.enqueue(new Callback<ResponseBody>() {
    @Override
    public void onResponse(Response<ResponseBody> response) {
        try {
            System.out.println(response.body().string());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onFailure(Throwable t) {
        e.printStackTrace();
    }
});

注意 上面的代码对响应对象调用了string(),它将整个响应读入一个字符串.如果您将主体传递给可以摄取流的东西,您可以调用 charStream() 代替.请参阅 ResponseBody 文档.

Note The code above calls string() on the response object, which reads the entire response into a String. If you are passing the body off to something that can ingest streams, you can call charStream() instead. See the ResponseBody docs.