简体   繁体   中英

GSON @SerializedName to get value from inner array in json

This is my json

{
   name: "mark"
   subject: "maths"
   phone: 123-456-7890
   email_addresses: [ { email: "mark@example.com", is_primary: true } ]
}

My java class goes like this

public class Student {
  @SerializedName("name") private String mName;
  @SerializedName("subject") private String mSubject;
  @SerializedName("phone") private String mPhone;
  private String mEmail;
}

Is there a way for to use @SerializedName for mEmail, so that I would be able to get the email field from the first object in the email_addresses array

No, there isn't. Either create your own TypeAdapter or create a POJO type for email addresses and have Student declare a field of type List of whatever that POJO type is. Provider a getter to only retrieve the first email (if there is one).

Create an innner static object and reference it that way (works for Android... (don't forget to make your object implement Parcelable)

 @SerializedName("email_addresses") 
 private EmailAdresses mEmailAdresses;   

 public static class EmailAdresses {

        @SerializedName("email")
        private String mEmail;
        @SerializedName("is_primary")
        private boolean mIsPrimary;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM