x-treme
x-treme

Reputation: 1636

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: "[email protected]", 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

Upvotes: 1

Views: 1463

Answers (2)

Greg
Greg

Reputation: 709

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;
}

Upvotes: 1

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280102

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).

Upvotes: 0

Related Questions