将对象添加到GSON数组android studio

时间:2019-06-26 04:59:37

标签: android gson

大家好,我正在使用android的gson库来解析我的JSON。一切工作正常,因为我选择了目标数组,有时它充满了值,有时是一个空数组。当数组为空时,我想在尝试添加其索引时推送对象初始化

selected_goal.add(INDEX,VALUE)

我想将一个物品推到有价值的地方,请帮助我该怎么做……

这是我的pojo:

 public class SelectedGoal {

        @SerializedName("id")
        @Expose
        private String id;
        @SerializedName("goal_name")
        @Expose
        private String goalName;
        @SerializedName("image")
        @Expose
        private String image;
        @SerializedName("position")
        @Expose
        private String position;
        @SerializedName("athlete_id")
        @Expose
        private String athleteId;
        @SerializedName("coach_id")
        @Expose
        private String coachId;
        @SerializedName("current_goal_id")
        @Expose
        private String currentGoalId;

        public String getId() {
            return id;
        }

        public void setId(String id) {
            this.id = id;
        }

        public String getGoalName() {
            return goalName;
        }

        public void setGoalName(String goalName) {
            this.goalName = goalName;
        }

        public String getImage() {
            return image;
        }

        public void setImage(String image) {
            this.image = image;
        }

        public String getPosition() {
            return position;
        }

        public void setPosition(String position) {
            this.position = position;
        }

        public String getAthleteId() {
            return athleteId;
        }

        public void setAthleteId(String athleteId) {
            this.athleteId = athleteId;
        }

        public String getCoachId() {
            return coachId;
        }

        public void setCoachId(String coachId) {
            this.coachId = coachId;
        }

        public String getCurrentGoalId() {
            return currentGoalId;
        }

        public void setCurrentGoalId(String currentGoalId) {
            this.currentGoalId = currentGoalId;
        }

    }

1 个答案:

答案 0 :(得分:1)

selected_goal.add(INDEX,new SelectedGoal());

EDIT-要设置值,请像您在SelectedGoal类中构造器。

public SelectedGoal(String id, String goalName, String image, String 
position, String athleteId, String coachId, String currentGoalId) {
    this.id = id;
    this.goalName = goalName;
    this.image = image;
    this.position = position;
    this.athleteId = athleteId;
    this.coachId = coachId;
    this.currentGoalId = currentGoalId;
}

最终将您的对象添加到列表中。

 selected_goal.add(INDEX,new SelectedGoal(id,goalName,image,position,athleteId,coachId,currentGoalId));