首页 > 解决方案 > 将对象添加到 GSON 数组 android studio

问题描述

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

selected_goal.add(INDEX,VALUE)

我想在有价值的地方推送一个对象,请帮助我该怎么做......</p>

这是我的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;
        }

    }

标签: androidgson

解决方案


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

编辑-要设置值,请在 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));

推荐阅读