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

有帮助吗?

解决方案 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));

其他提示

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);
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top