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
Class HttpLoggingInterceptorAn OkHttp interceptor which logs request and response information.
Overview. Retrofit is a type-safe REST client for Android, Java and Kotlin developed by Square.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With