How do I convert a successful Response body to a specific type using retrofit?

前端 未结 1 1641
囚心锁ツ
囚心锁ツ 2021-01-04 09:43

In async mode retrofit calls

public void success(T t, Response rawResponse)

were t is the converted response, and rawResponse is the raw r

相关标签:
1条回答
  • 2021-01-04 10:04

    Here's an example of a StringConverter class that implements the Converter found in retrofit. Basically you'll have to override the fromBody() and tell it what you want.

    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();
        }
    }
    

    Applying this to your request you'll have to do the following:

    // initializing Retrofit's rest adapter
    RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint(ApiConstants.MAIN_URL).setLogLevel(LogLevel.FULL)
            .setConverter(new StringConverter()).build();
    
    0 讨论(0)
提交回复
热议问题