如何在Retrofit 2中打印漂亮的照片?

我有我的改造设置HttpLoggingInterceptor像这样:

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

在我的Gson实例上,我做了setPrettyPrinting ,我仍然得到紧凑的JSON输出。 这是我的图书馆。

 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' 

如何使用Retrofit 2实现漂亮的打印? 谢谢。

编辑:更新我的图书馆,仍然没有工作

创建您自己的自定义HttpLogginInterceptor。

 public class CustomHttpLogging implements HttpLoggingInterceptor.Logger { @Override public void log(String message) { final String logName = "OkHttp"; if (!message.startsWith("{")) { Log.d(logName, message); return; } try { String prettyPrintJson = new GsonBuilder().setPrettyPrinting().create().toJson(new JsonParser().parse(message)); Log.d(logName, prettyPrintJson); } catch (JsonSyntaxException m) { Log.d(logName, message); } } } 

在你的客户端中,添加:

 OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(new CustomHttpLogging()) .build(); 

Beta 2并不总是尊重自定义的gson设置。 尝试升级到Beta 3。

从测试版3更改日志 –

修复:Gson转换器现在尊重提供的Gson实例上的设置(如serializeNulls)。 这需要Gson 2.4或更高版本。

您还需要升级到okhttp3 beta3。

受Tanapruk的回答的启发,这是我所做的,使我的版本的翻新(2.1.0)和okhttp.logging拦截器(3.8.1)。 对不起Kotlin和Java的混合。

该版本适用于打印JSON对象和数组。

 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 } } } 

而在客户端:

 OkHttpClient.Builder httpClientBuilder = new OkHttpClient.Builder(); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new ApiLogger()); httpLoggingInterceptor.setLevel(Level.BODY); httpClientBuilder.addInterceptor(httpLoggingInterceptor);