{"id":7780,"date":"2015-10-25T20:05:46","date_gmt":"2015-10-25T20:05:46","guid":{"rendered":"https:\/\/unknownerror.org\/index.php\/2015\/10\/25\/how-can-i-return-string-or-jsonobject-from-asynchronous-callback-using-retrofit-open-source-projects-square-retrofit\/"},"modified":"2015-10-25T20:05:46","modified_gmt":"2015-10-25T20:05:46","slug":"how-can-i-return-string-or-jsonobject-from-asynchronous-callback-using-retrofit-open-source-projects-square-retrofit","status":"publish","type":"post","link":"https:\/\/unknownerror.org\/index.php\/2015\/10\/25\/how-can-i-return-string-or-jsonobject-from-asynchronous-callback-using-retrofit-open-source-projects-square-retrofit\/","title":{"rendered":"How can I return String or JSONObject from asynchronous callback using Retrofit?-open source projects square\/retrofit"},"content":{"rendered":"<p><img decoding=\"async\" src=\"http:\/\/i.stack.imgur.com\/fHXdY.jpg?s=128&amp;g=1\" \/> <strong>lordmegamax<\/strong><\/p>\n<p>I figured it out. It&#8217;s embarrassing but it was very simple&#8230; <strong>Temporary solution<\/strong> may be like this:<\/p>\n<pre><code> public void success(Response response, Response ignored) {\n            TypedInput body = response.getBody();\n            try {\n                BufferedReader reader = new BufferedReader(new InputStreamReader(body.in()));\n                StringBuilder out = new StringBuilder();\n                String newLine = System.getProperty(\"line.separator\");\n                String line;\n                while ((line = reader.readLine()) != null) {\n                    out.append(line);\n                    out.append(newLine);\n                }\n\n                \/\/ Prints the correct String representation of body. \n                System.out.println(out);\n            } catch (IOException e) {\n                e.printStackTrace();\n            }\n        }\n<\/code><\/pre>\n<p>But if you want to get directly Callback the <strong>Better way<\/strong> is to use Converter.<\/p>\n<pre><code>public class Main {\npublic interface ApiService {\n    @GET(\"\/api\/\")\n    public void getJson(Callback callback);\n}\n\npublic static void main(String[] args) {\n    RestAdapter restAdapter = new RestAdapter.Builder()\n            .setClient(new MockClient())\n            .setConverter(new StringConverter())\n            .setEndpoint(\"http:\/\/www.example.com\").build();\n\n    ApiService service = restAdapter.create(ApiService.class);\n    service.getJson(new Callback() {\n        @Override\n        public void success(String str, Response ignored) {\n            \/\/ Prints the correct String representation of body.\n            System.out.println(str);\n        }\n\n        @Override\n        public void failure(RetrofitError retrofitError) {\n            System.out.println(\"Failure, retrofitError\" + retrofitError);\n        }\n    });\n}\n\nstatic class StringConverter implements Converter {\n\n    @Override\n    public Object fromBody(TypedInput typedInput, Type type) throws ConversionException {\n        String text = null;\n        try {\n            text = fromStream(typedInput.in());\n        } catch (IOException ignored) {\/*NOP*\/ }\n\n        return text;\n    }\n\n    @Override\n    public TypedOutput toBody(Object o) {\n        return null;\n    }\n\n    public static String fromStream(InputStream in) throws IOException {\n        BufferedReader reader = new BufferedReader(new InputStreamReader(in));\n        StringBuilder out = new StringBuilder();\n        String newLine = System.getProperty(\"line.separator\");\n        String line;\n        while ((line = reader.readLine()) != null) {\n            out.append(line);\n            out.append(newLine);\n        }\n        return out.toString();\n    }\n}\n\npublic static class MockClient implements Client {\n    @Override\n    public Response execute(Request request) throws IOException {\n        URI uri = URI.create(request.getUrl());\n        String responseString = \"\";\n\n        if (uri.getPath().equals(\"\/api\/\")) {\n            responseString = \"{result:\\\"ok\\\"}\";\n        } else {\n            responseString = \"{result:\\\"error\\\"}\";\n        }\n\n        return new Response(request.getUrl(), 200, \"nothing\", Collections.EMPTY_LIST,\n                new TypedByteArray(\"application\/json\", responseString.getBytes()));\n    }\n  }\n}\n<\/code><\/pre>\n<p>If you know how to improve this code &#8211; please feel free to write about it.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>lordmegamax I figured it out. It&#8217;s embarrassing but it was very simple&#8230; Temporary solution may be like this: 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(&#8220;line.separator&#8221;); String line; while ((line = reader.readLine()) != null) { [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[1],"tags":[],"class_list":["post-7780","post","type-post","status-publish","format-standard","hentry","category-uncategorized"],"_links":{"self":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7780","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/comments?post=7780"}],"version-history":[{"count":0,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/posts\/7780\/revisions"}],"wp:attachment":[{"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/media?parent=7780"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/categories?post=7780"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/unknownerror.org\/index.php\/wp-json\/wp\/v2\/tags?post=7780"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}