简体   繁体   中英

Retrofit How To Print Out Response JSON

I'm using Retrofit and I want to get access to the JSON response that is returned from the server. Could someone please advise me. Thanks

if you only want to see the respones for debugging purpose just turn on debugging in retrofit and look at the log. It's something like:

restAdapter.setDebuggingEnabled(true);

If you need access to the direct response in code all of the time, you should be doing that at the httpclient level as it's basically bypassing the purpose of retrofit

To print the response object first change the callback object type to the generic Object type via Callback<Object> cb . Then in your success callback you can just log the object to print the Json formatted version to the console.

@Override
public void success(Object o, Response response) {
    Log.i("Tag", "Login data " + o.toString());
}

To print the request object you can use whatever Json library you use (here I'm using Gson ) to serialize the request object to Json and log that to the console.

Log.i("Tag", "Request data " + new Gson().toJson(requestObject));

You need to get response in string format and then parse data using gson. To get String response you can use CustomStringConverter by extending retrofit.converter.Converter or just get the inputstream from the response on success result.

public void success(Response r1, Response r2) {

    IntputStream in  = r1.getBody().in()
       //convert this inputstream to string
}

If you want to use full power of Retrofit and keep the raw input for yourself (eg to save it in persistent cache), you can extend the Converter , eg

RestAdapter restAdapter = new RestAdapter.Builder()
    .setConverter(new GsonConverter(gson) {
        @Override
        public Object fromBody(TypedInput body, Type type) throws ConversionException {
            try {
                byte[] buffer = new byte[body.length()];
                body.in().read(buffer);
                body.in().reset();
            }
            catch (IOException e) {
                throw new ConversionException(e);
            }
            return super.fromBody(body, type);
        }
    })
    ...build();
ResponseInterface ri = restAdapter.create(ResponseInterface.class);

You can also log the result like this

mRestAdapter = new RestAdapter.Builder()
            .setEndpoint(getBaseUrl())
            .setLogLevel(RestAdapter.LogLevel.FULL) //Log the result
            .build();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM