【问题标题】:How convert a POJO into a readable string on Android for debugging?如何将 POJO 转换为 Android 上的可读字符串以进行调试?
【发布时间】:2018-05-29 23:20:10
【问题描述】:

给定以下纯文本 JSON 对象

class Chat {

    String id;
    String title;
    List<String> messages;

}

如何覆盖 toString 以使其仅在调试时可读

【问题讨论】:

    标签: android json gson


    【解决方案1】:

    只需将此添加到聊天中

    @Override
    public String toString() {
        return "\nIngrediente{" +
                "\n\tid='" + id + '\'' +
                "\n\ttitle='" + title + '\'' +
                "\n\tmessages=" + messages +
                "\n}";
    }
    

    注意ArrayList已经可以打印了,此时你可以很容易地

    Chat chat = new Chat();
    Log.d("Printing!", chat);
    

    为我工作。

    更新

    前段时间我用过这个toString,我在stackoverflow上找到了它并稍微编辑了一下,但我不记得源链接了:

    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        String newLine = System.getProperty("line.separator");
    
        result.append( this.getClass().getName() );
        result.append( " Object {" );
        result.append(newLine);
    
        //determine fields declared in this class only (no fields of superclass)
        Field[] fields = this.getClass().getDeclaredFields();
    
        //print field names paired with their values
        for ( Field field : fields  ) {
            result.append("  ");
            try {
                if (field.isSynthetic() || field.getName().equals("serialVersionUID"))
                    continue;
                result.append( field.getName() );
                result.append(": ");
                //requires access to private field:
                result.append( field.get(this) );
            } catch ( IllegalAccessException ex ) {
                System.out.println(ex);
            }
            result.append(newLine);
        }
        result.append("}");
    
        return result.toString();
    }
    

    稍微调整一下,您实际上可以打印任何 pojo 中的所有属性,而不必每次都将它们添加到 toString

    【讨论】:

    • 使用这种方法,每次我向Chat 类添加/删除属性时,都必须修改toString。此外,不需要缩进String,因为我们可以使用编程编辑器美化它。
    • 已更新,我添加了一种自动打印所有字段的方法。
    【解决方案2】:

    您自己的解决方案有效,但不是太通用。我会创建一个辅助类(如果不想在每次打印时都内联)

    public class PrettyPrinter {
    
       private static final Gson gson = new GsonBuilder()
             .setPrettyPrinting().create();
    
       public static String print(Object o) {
          return gson.toJson(o);
       }
    
    }
    

    这样你就可以了

    PrettyPrinter.print(chat);
    

    如果你坚持使用toString(),那就是

    @Override
    public String toString() {
       return isDebugEnabled() ? PrettyPrinter.print(this) : super.toString();
       // or BuildConfig.DEBUG ? ...;
    }
    

    或者也许你想通过扩展这样的类来实现它

    public class JsonPrintable {
    
       public String toString() {
          return isDebugEnabled() ? PrettyPrinter.print(this) : super.toString();
       }
       /**
        * this should be logging dependent implementation
        * @return
        */
       public boolean isDebugEnabled() {
          return log.isDebugEnabled(); // personally use slf4j for logging... 
          // or return BuildConfig.DEBUG;
       } 
    }
    

    所以

    public class Chat extends JsonPrintable { ... }
    

    【讨论】:

    • 更新的答案缺少调试检查
    【解决方案3】:

    您可以将其序列化为 JSON 字符串:

    class Chat {
    
        private static final GSON = new GSON();
    
        String id;
        String title;
        List<String> messages;
    
        public String toString() {
            return BuildConfig.DEBUG ? GSON.toJson(this) : super.toString();
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2017-05-20
      • 1970-01-01
      • 1970-01-01
      • 2012-06-15
      • 2016-06-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-27
      • 1970-01-01
      相关资源
      最近更新 更多