问题
Given a the following plain-text JSON object
class Chat {
String id;
String title;
List<String> messages;
}
how to I override toString in order to it be human readable only for debugging?
回答1:
You could serialize it into a JSON string:
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();
}
}
回答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)
public class PrettyPrinter {
private static final Gson gson = new GsonBuilder()
.setPrettyPrinting().create();
public static String print(Object o) {
return gson.toJson(o);
}
}
so you can
PrettyPrinter.print(chat);
If you insist to use toString() it would then be
@Override
public String toString() {
return isDebugEnabled() ? PrettyPrinter.print(this) : super.toString();
// or BuildConfig.DEBUG ? ...;
}
or maybe you want to make it by extending a class like this
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;
}
}
so
public class Chat extends JsonPrintable { ... }
回答3:
Simply add this to Chat
@Override
public String 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
Chat chat = new Chat();
Log.d("Printing!", chat);
Works for me.
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:
@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();
}
tweaking it a little you can actually print all the property in any pojo without having to add them every time to toString
来源:https://stackoverflow.com/questions/47837569/how-convert-a-pojo-into-a-readable-string-on-android-for-debugging