Question

I have multiple classes with toString: some of these have collections.

Is this a good idea to create toString with gson?

@Override
public String toString() {
    return new Gson().toJson(this);
}

I use toString for logging with log4j. I don't want exceptions on toString output. Anyone use this implementation?

Maybe it's a duplicate question, but I don't find the right answer

Was it helpful?

Solution 2

Gson output may be "large" on collections with complex objects.

After evaluate some scenarios, I prefer to use Gson only in specific points.

log.info("[context scenario] Collection<Foo>" + new Gson().toJson(foos));

OTHER TIPS

You may want to consider Apache Common's Reflection toString Builder. It should be faster than Gson, but still not need to be modified when you add new fields to the model.

@Override
public String toString() {
     return ReflectionToStringBuilder.toString(this);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top