android - 将对象添加到 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;
}
}
解决方案
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));
推荐阅读
- swift - Xcode:如何找到没有重用标识符的单元格
- android - 我的应用在谷歌登录时崩溃
- ssis - 从循环中的过程输出变量填充的 SSIS 包范围变量
- php - 使用php从模式内的第二个sql表中检索数据
- azure - 将点到站点与 Azure VPN 网关一起使用时的私有 DNS 方法?
- excel - excel中格式为YYYY-mm-dd hh:mm:ss.ffffff的两个时间戳之间的时间差
- android - 添加点击通知操作的日志
- cluster-analysis - Weka ClusterMembership 过滤器只给出 1 和 0 的概率
- python - 使用 (arr.transpose() == arr).all() 的意外对称测试结果
- mysql - 计算每个人被分配到的活动