Skip to content Skip to sidebar Skip to footer

How Convert A Pojo Into A Readable String On Android For Debugging?

Given a the following plain-text JSON object class Chat { String id; String title; List messages; } how to I override toString in order to it be human

Solution 1:

You could serialize it into a JSON string:

classChat {

    privatestatic final GSON = newGSON();

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

    publicStringtoString() {
        returnBuildConfig.DEBUG ? GSON.toJson(this) : super.toString();
    }

}

Solution 2:

Your own solution works but it is not too generic. I would create a helper class (if not want to do inline on every print)

publicclassPrettyPrinter{

   privatestaticfinal Gson gson = new GsonBuilder()
         .setPrettyPrinting().create();

   publicstaticStringprint(Object o) {
      return gson.toJson(o);
   }

}

so you can

PrettyPrinter.print(chat);

If you insist to use toString() it would then be

@OverridepublicStringtoString() {
   returnisDebugEnabled() ? PrettyPrinter.print(this) : super.toString();
   // or BuildConfig.DEBUG ? ...;
}

or maybe you want to make it by extending a class like this

publicclassJsonPrintable {

   publicStringtoString() {
      returnisDebugEnabled() ? PrettyPrinter.print(this) : super.toString();
   }
   /**
    * this should be logging dependent implementation
    * @return
    */publicbooleanisDebugEnabled() {
      return log.isDebugEnabled(); // personally use slf4j for logging... // or return BuildConfig.DEBUG;
   } 
}

so

publicclassChatextendsJsonPrintable { ... }

Solution 3:

Simply add this to Chat

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

note that ArrayList are already printable, at this point you can easily

Chatchat=newChat();
Log.d("Printing!", chat);

Works for me.

enter image description here

UPDATE

I used this toString a while ago, i found it on stackoverflow and edited it a little but i don't remember the source link:

@Overridepublic 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 valuesfor ( 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();
}

tweaking it a little you can actually print all the property in any pojo without having to add them every time to toString

Post a Comment for "How Convert A Pojo Into A Readable String On Android For Debugging?"