This is how you overload the toString() method:
public class Person extends Object {
@Override
public final String toString() {
Gson gson = new GsonBuilder().serializeNulls().create();
return (gson.toJson(this));
}
}
In this example I get a JSON string when calling the toString() method of Person instead of the default string representation of an Object.
But what if I have an array of Person like:
Person[] persons = new Person[3];
System.out.println(persons.toString());
What do I have to do or which method(s) do I have to override in that case?
解决方案
You cannot override default array's toString. If you want to convert an array of objects into the string, use Arrays.toString().