Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pretty print in Retrofit 2?

I have my retrofit set up with HttpLoggingInterceptor like this:

Gson gson = new GsonBuilder()
                .setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
                .setPrettyPrinting() // Pretty print
                .create();

HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
                .addInterceptor(interceptor)
                .build();

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .client(client)
                .build();

On my Gson instance, I did setPrettyPrinting and I still get compact JSON outputs. Here are my libraries.

compile 'com.google.code.gson:gson:2.5'
compile 'com.squareup.retrofit2:converter-gson:2.0.0-beta4'
compile 'com.squareup.okhttp3:logging-interceptor:3.0.1'

compile 'com.squareup.retrofit2:retrofit:2.0.0-beta4'
compile 'com.squareup.okhttp3:okhttp:3.0.1'

How can I acheive pretty printing using Retrofit 2? Thanks.

EDIT: Updated my libraries and still didn't work

like image 848
Schinizer Avatar asked Jan 26 '16 03:01

Schinizer


People also ask

What is HttpLoggingInterceptor?

Class HttpLoggingInterceptorAn OkHttp interceptor which logs request and response information.

Is retrofit RESTful?

Overview. Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square.


1 Answers

Inspired by Tanapruk's answer this is what I did to make it work with my versions of retrofit (2.1.0) and okhttp.logging-interceptor (3.8.1).

This version works for printing both JSON objects and arrays.

class ApiLogger : HttpLoggingInterceptor.Logger {
    override fun log(message: String) {
        val logName = "ApiLogger"
        if (message.startsWith("{") || message.startsWith("[")) {
            try {
                val prettyPrintJson = GsonBuilder().setPrettyPrinting()
                    .create().toJson(JsonParser().parse(message))
                Log.d(logName, prettyPrintJson)
            } catch (m: JsonSyntaxException) {
                Log.d(logName, message)
            }
        } else {
            Log.d(logName, message)
            return
        }
    }
}

And in the client:

val httpClientBuilder = OkHttpClient.Builder()
val httpLoggingInterceptor = HttpLoggingInterceptor(ApiLogger())
httpLoggingInterceptor.level = Level.BODY
httpClientBuilder.addInterceptor(httpLoggingInterceptor)
like image 132
Anders Ullnæss Avatar answered Oct 21 '22 17:10

Anders Ullnæss