문제

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