tortal tortal - 1 year ago 73
Java Question

OK to use JSON output as default for toString()?

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?

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.

Answer Source

There's no harm in doing it this way. I would suggest you to create a static variable for your Gson instance and enable pretty printing:

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

This way the output from toString method will be formatted.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download