tortal tortal - 3 months ago 7
Java Question

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

@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.

Answer

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.