use
Both methods are to convert Java objects into JSON string format
The difference is that () is the method in Alibaba's package
() is a method in Google's package
The pits that have been stepped on
Friends who are nagging can read the analysis directly! !
The code is like this
public class Person{ String name; String father; String mother; } public class Student extends Person{ String name; Integer age; }
Two entity classes, one Person class, and one Student class inherits the Person class, and the name field in the Student class will override the name field in the Person class.
When using the Student entity class object using the() method, an error will be reported.
The error content is:
: class Student declares multiple JSON fields named name
The code for the example is as follows:
Student student = new Student(); ("Zhang San"); (18); Gson G = new Gson(); (student);
The above code will report an error, but it can run normally using Alibaba's JSON class, as follows:
Student student = new Student(); ("Zhang San"); (18); (Student);
analyze
The specific reason is that Student inherits the Person class and overwrites the original name. In the process of converting it to a JSON string, Google's () method cannot distinguish whether it is the name in Person or the name in Student, so the above-mentioned error occurs. However, Alibaba's () method will convert the attribute value in the subclass by default, so there will be no error.
Personally, I suggest that JSON-related processing use Alibaba’s JSON class! ! !
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.