【问题标题】:How to pretty print in Retrofit 2?如何在 Retrofit 2 中进行漂亮的打印?
【发布时间】:2016-01-26 03:34:51
【问题描述】:

我使用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 实现漂亮的打印效果? 谢谢。

编辑:更新了我的库,但仍然没有工作

【问题讨论】:

    标签: android gson retrofit2


    【解决方案1】:

    受 Tanapruk 回答的启发,这是我为使其适用于我的改造 (2.1.0) 和 okhttp.logging-interceptor (3.8.1) 版本所做的工作。

    此版本适用于打印 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
            }
        }
    }
    

    在客户端:

    val httpClientBuilder = OkHttpClient.Builder()
    val httpLoggingInterceptor = HttpLoggingInterceptor(ApiLogger())
    httpLoggingInterceptor.level = Level.BODY
    httpClientBuilder.addInterceptor(httpLoggingInterceptor)
    

    【讨论】:

    • 如果 JSON 很长,它将被截断,您可以像这样逐行记录:´prettyPrintJson.lines().forEach { Log.d(logName, it) }´跨度>
    【解决方案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();
    

    【讨论】:

      【解决方案3】:

      感谢 Tanapruk Tangphianphan 的回答。

      我改进它以支持所有Java Platform,而不仅仅是Android

      创建 PrettyLogger 类

      class PrettyLogger implements HttpLoggingInterceptor.Logger {
          private Gson mGson = new GsonBuilder().setPrettyPrinting().create();
          private JsonParser mJsonParser = new JsonParser();
      
          @Override
          public void log(String message) {
              String trimMessage = message.trim();
              if ((trimMessage.startsWith("{") && trimMessage.endsWith("}"))
                      || (trimMessage.startsWith("[") && trimMessage.endsWith("]"))) {
                  try {
                      String prettyJson = mGson.toJson(mJsonParser.parse(message));
                      Platform.get().log(INFO, prettyJson, null);
                  } catch (Exception e) {
                      Platform.get().log(WARN, message, e);
                  }
              } else {
                  Platform.get().log(INFO, message, null);
              }
          }
      }
      

      在 Buidler 中使用:

      OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
      HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(new PrettyLogger());
      loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
      builder.addInterceptor(loggingInterceptor);
      

      【讨论】:

        【解决方案4】:

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

        来自beta 3 change log——

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

        您还需要为 beta3 升级到 okhttp3。

        【讨论】:

        • 用最新的 beta4 试过了,还是不行。
        【解决方案5】:

        不使用 gson 的 Kotlin 版本:

        HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
        
            private fun print(m: String) {
                //Crashlytics.log(m)
                Log.i("API", m)
            }
        
            override fun log(message: String) {
                if (message.length > 500)
                    return print("=== more than 500 characters ===")
        
                if (message.startsWith("{") || message.startsWith("[")) try {
                        JSONObject(message).toString(4).also(::print)
                    } catch (e: JSONException) { print(message) }
                else print(message)
            }
        }).also { it.level = HttpLoggingInterceptor.Level.BODY }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2021-02-13
          • 1970-01-01
          • 2010-11-14
          • 1970-01-01
          • 2014-07-03
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多