2016-01-26 4 views
5

私は私の改造は、このようなHttpLoggingInterceptorに設定している:私のGsonインスタンス上Retrofit 2できれいに印刷するには?

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

、私は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を使用してきれいな印刷を達成するにはどうすればよいですか?おかげさまで

EDITは:私のライブラリを更新し、まだ

答えて

0

ベータ2が常にカスタムgson設定を尊重していない動作しませんでした。 beta 3 change logからベータ3

にアップグレードしてみてください -

修正:Gsonコンバータは今(などserializeNullsなど)供給Gson インスタンスの設定を尊重します。これにはGson 2.4以降が必要です。

また、beta3の場合はokhttp3にアップグレードする必要があります。

+0

は、最新beta4にしようと、それはまだ動作しませんでした。 – Schinizer

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

、追加:このTanaprukの答えに触発さ

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

を(私はそれが改造(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); 
関連する問題