@SerializedName comment

In Android Gson parsing the data parses json is convenient, the data can be directly resolved into json java object or collection.
  Gson json analytic methods not described in detail here I am online a lot of examples, I am here mainly talk about using @SerializedName be annotated.
  Gson resolved using default when the object is resolved into json json value to the attribute in the corresponding field in which the corresponding field java object. Then we often encounter our own java objects defined in the attribute name with json in the field name is not the same, this is how to do it, then we can use @SerializedName annotations to objects in the property with json match up the corresponding values in the field.
  Here to talk about the specific use:
  We have some json data as follows:

  1. {
  2. "id":"1"
  3. "n":"zhangsan"
  4. "p":"123456"
  5. "s":"0"
  6. }

 

  This is a user data includes id, user name, password, gender, if a normal user class to parse these words is this:

  1. public class User{
  2. private String id;
  3. private String n;
  4. private String p;
  5. private String s;
  6. }

  User class to write directly to Gson resolved directly, but then the class attribute named User-friendly is less, then how do we want it? Gson provide annotation method to solve this problem @SerializedName, used as follows:

  1. public class User{
  2.  
  3. private String id;
  4.  
  5. @SerializedName("n")
  6. private String userName;
  7.  
  8. @SerializedName("p")
  9. private String password;
  10.  
  11. @SerializedName("s")
  12. private String sex;
  13. }

  Such re-use Gson will be resolved when n corresponding value is assigned to the userName attribute the same if we want to generate json string using Gson User generated when userName name will also generate n. This would solve the situation with java object in json property names in the field names do not match.

Guess you like

Origin blog.csdn.net/pzq915981048/article/details/97117236