如何使用改造将成功的响应主体转换为特定类型?

时间:2014-10-24 19:52:18

标签: android retrofit

在异步模式下改装调用

public void success(T t, Response rawResponse)

是转换后的响应,rawResponse是原始响应。这使您可以访问原始响应和转换后的响应。

在同步模式下,您可以获得转换后的响应 OR 原始响应

转换后的回复

@GET("/users/list")
List<User> userList();

原始回复

@GET("/users/list")
Response userList();

Response对象确实有一个获取正文的方法

TypedInput  getBody()

并且改装api确实有一个可以将其转换为java对象的转换器类

Object fromBody(TypedInput body,Type type)

但我无法弄清楚如何获取Converter对象的实例

我可能能够创建Converter类的实例,但这需要知道用于创建RestAdapter的Gson对象,我可能无法访问它。理想情况下,我想直接获取对转换器对象的引用RestAdpater。


以下任何一项都将回答我的问题:

  1. 有没有办法获得对改造使用的默认转换器的引用?
  2. 有谁知道如何构建默认的Converter? (没有默认构造函数,有两个构造函数public GsonConverter(Gson gson)和公共GsonConverter(Gson gson,String charset)
  3. 还有其他方法可以同步模式同时获取原始响应和转换响应吗?

1 个答案:

答案 0 :(得分:8)

以下是实现改造中发现的StringConverter的{​​{1}}类的示例。基本上你必须覆盖Converter并告诉它你想要什么。

fromBody()

将此应用于您的请求,您必须执行以下操作:

public class StringConverter implements Converter {

    /*
     * In default cases Retrofit calls on GSON which expects a JSON which gives
     * us the following error, com.google.gson.JsonSyntaxException:
     * java.lang.IllegalStateException: Expected BEGIN_OBJECT but was
     * BEGIN_ARRAY at line x column x
     */

    @Override
    public Object fromBody(TypedInput typedInput, Type type)
            throws ConversionException {

        String text = null;
        try {
            text = fromStream(typedInput.in());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return text;
    }

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

    // Custom method to convert stream from request to string
    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();
    }
}