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

Était-ce utile?

La 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));

Autres conseils

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);
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top