@Override
public String toString() {
return new Gson().toJson(this);
}
Am I breaking some good practice, "Joshua"-pattern thing, general design pattern or other convention by simply doing this as default behavior for my model objects?
toString()
will anyhow only be used in debugging in the paradigm (Android) that we are currently using. That's also the reason why I like seeing the object in JSON since much ORM/json persistence will be happening through http->php/python->mysql and to the local SQLite.
Yes. It's OK to use GSON/Jackson/Reflections library to implement toString() method.
There are few ways to implement toString method.
Reflections (Apache library)
@Override
public String toString(){
return org.apache.commons.lang3.builder.ReflectionToStringBuilder.toString(this);
}
JSON based implementation (GSON, Jackson libraries)
// GSON library for JSON
@Override
public String toString(){
return new com.google.gson.Gson().toJson(this);
}
// Jackson libabry for JSON/YAML
@Override
public String toString() {
try {
return new com.fasterxml.jackson.databind.ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
ToStringBuilder (available with apache-commons library)
@Override
public String toString() {
return new org.apache.commons.lang3.builder.ToStringBuilder(this).
append("field1", field1).
append("field2", field2).
toString();
}
Hard-core toString() implementation
@Override
public String toString() {
return new StringBuilder()
.append("field1:"+field1)
.append("field2:"+field2)
.toString();
}
Lombok annotations : Generates toString() at compile time
import lombok.ToString;
@ToString
public class ToStringExample {}