如何使用Retrofit从异步回调中返回String或JSONObject?

lor*_*max 45 android retrofit retrofit2

例如,打电话

api.getUserName(userId, new Callback<String>() {...});
Run Code Online (Sandbox Code Playgroud)

原因:

retrofit.RetrofitError: retrofit.converter.ConversionException:
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 
Expected a string but was BEGIN_OBJECT at line 1 column 2
Run Code Online (Sandbox Code Playgroud)

我想我必须禁用gson解析到POJO但无法弄清楚如何做到这一点.

lor*_*max 49

我想到了.这很尴尬,但很简单...... 临时解决方案可能是这样的:

 public void success(Response response, Response ignored) {
            TypedInput body = response.getBody();
            try {
                BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()));
                StringBuilder out = new StringBuilder();
                String newLine = System.getProperty("line.separator");
                String line;
                while ((line = reader.readLine()) != null) {
                    out.append(line);
                    out.append(newLine);
                }

                // Prints the correct String representation of body. 
                System.out.println(out);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是如果你想直接获得Callback,那么更好的方法就是使用Converter.

public class Main {
public interface ApiService {
    @GET("/api/")
    public void getJson(Callback<String> callback);
}

public static void main(String[] args) {
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setClient(new MockClient())
            .setConverter(new StringConverter())
            .setEndpoint("http://www.example.com").build();

    ApiService service = restAdapter.create(ApiService.class);
    service.getJson(new Callback<String>() {
        @Override
        public void success(String str, Response ignored) {
            // Prints the correct String representation of body.
            System.out.println(str);
        }

        @Override
        public void failure(RetrofitError retrofitError) {
            System.out.println("Failure, retrofitError" + retrofitError);
        }
    });
}

static class StringConverter implements Converter {

    @Override
    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {
        String text = null;
        try {
            text = fromStream(typedInput.in());
        } catch (IOException ignored) {/*NOP*/ }

        return text;
    }

    @Override
    public TypedOutput toBody(Object o) {
        return null;
    }

    public static String fromStream(InputStream in) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder out = new StringBuilder();
        String newLine = System.getProperty("line.separator");
        String line;
        while ((line = reader.readLine()) != null) {
            out.append(line);
            out.append(newLine);
        }
        return out.toString();
    }
}

public static class MockClient implements Client {
    @Override
    public Response execute(Request request) throws IOException {
        URI uri = URI.create(request.getUrl());
        String responseString = "";

        if (uri.getPath().equals("/api/")) {
            responseString = "{result:\"ok\"}";
        } else {
            responseString = "{result:\"error\"}";
        }

        return new Response(request.getUrl(), 200, "nothing", Collections.EMPTY_LIST,
                new TypedByteArray("application/json", responseString.getBytes()));
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如果您知道如何改进此代码 - 请随时写一下.


TPo*_*hel 32

一种可能的解决办法是使用JsonElement作为Callback式(Callback<JsonElement>).在您的原始示例中:

api.getUserName(userId, new Callback<JsonElement>() {...});
Run Code Online (Sandbox Code Playgroud)

在成功方法中,您可以将其转换JsonElement为a String或a JsonObject.

JsonObject jsonObj = element.getAsJsonObject();
String strObj = element.toString();
Run Code Online (Sandbox Code Playgroud)


flo*_*cat 30

Retrofit 2.0.0-beta3增加了一个converter-scalars模块,提供了一个 Converter.Factory转换String,8个基元类型和8个盒装基元类型作为text/plain主体.在普通转换器之前安装它,以避免将这些简单的标量通过,例如,JSON转换器.

因此,首先为您的应用程序添加converter-scalars模块到build.gradle文件.

dependencies {
    ...
    // use your Retrofit version (requires at minimum 2.0.0-beta3) instead of 2.0.0
    // also do not forget to add other Retrofit module you needed
    compile 'com.squareup.retrofit2:converter-scalars:2.0.0'
}
Run Code Online (Sandbox Code Playgroud)

然后,Retrofit像这样创建您的实例:

new Retrofit.Builder()
        .baseUrl(BASE_URL)
        // add the converter-scalars for coverting String
        .addConverterFactory(ScalarsConverterFactory.create())
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
        .build()
        .create(Service.class);
Run Code Online (Sandbox Code Playgroud)

现在你可以像这样使用API​​声明:

interface Service {

    @GET("/users/{id}/name")
    Call<String> userName(@Path("userId") String userId);

    // RxJava version
    @GET("/users/{id}/name")
    Observable<String> userName(@Path("userId") String userId);
}
Run Code Online (Sandbox Code Playgroud)


bgp*_*aya 21

答案可能比已经提到的要短得多,并且不需要任何额外的库:

声明使用Response如下:

... Callback<Response> callback);
Run Code Online (Sandbox Code Playgroud)

在处理响应时:

@Override
public void success(Response s, Response response) {
    new JSONObject(new String(((TypedByteArray) response.getBody()).getBytes()))
}
Run Code Online (Sandbox Code Playgroud)