使用struts-json时对象数组属性赋值仅保留最后值的问题排查
排查Struts-JSON返回仅最后一组id-text的问题
咱们从类结构设计和循环赋值逻辑两个核心方向入手,一步步定位问题:
1. 先确认类结构是否匹配你期望的JSON格式
你想要的是「多组id-text对象组成的results结构」,也就是results应该是一个对象数组(每个元素包含独立的id和text属性)。但目前你的ResultsOrganisationUnit用了两个独立数组Integer[] id和String[] text,这种设计转成JSON后是两个并行数组,和你预期的结构完全不同。
如果你的类是这种写法:
public class ResultsOrganisationUnit { private Integer[] id; private String[] text; // getter/setter }
生成的JSON会是:
{ "id": [1,2,3,4,5], "text": ["文本1","文本2","文本3","文本4","文本5"] }
但如果你想要的是每个元素都是id-text对象的数组,得调整类结构:
首先创建单个的id-text实体类:
public class IdTextPair { private Integer id; private String text; // 构造方法+getter/setter public IdTextPair(Integer id, String text) { this.id = id; this.text = text; } }
然后让结果类包含这个实体的集合:
public class ResultsOrganisationUnit { private List<IdTextPair> results; // getter/setter public ResultsOrganisationUnit() { this.results = new ArrayList<>(); } }
之后循环里直接往集合加对象就行,不会出现覆盖问题。
2. 检查循环赋值的逻辑错误
如果坚持用原有的双数组结构,大概率是赋值时没正确操作数组索引,反而每次都重新创建数组覆盖了之前的内容。比如错误写法:
ResultsOrganisationUnit res = new ResultsOrganisationUnit(); res.setId(new Integer[5]); res.setText(new String[5]); for (OrganisationUnit ou : children) { // 错误:每次都创建新的单元素数组,覆盖整个id/text数组,最后只剩最后一组值 res.setId(new Integer[]{ou.getId()}); res.setText(new String[]{ou.getText()}); }
正确的写法应该通过索引给数组元素赋值:
ResultsOrganisationUnit res = new ResultsOrganisationUnit(); int size = children.size(); res.setId(new Integer[size]); res.setText(new String[size]); int index = 0; for (OrganisationUnit ou : children) { res.getId()[index] = ou.getId(); res.getText()[index] = ou.getText(); index++; }
这样每个数组位置都会被正确赋值,不会被覆盖。
3. 验证Struts-JSON的序列化配置
还要确认Struts的JSON拦截器配置是否正确,比如有没有排除需要序列化的属性,或者是否开启了嵌套对象的深度序列化。可以在Action方法上添加注解确保属性被正确序列化:
public class YourAction extends ActionSupport { private ResultsOrganisationUnit resultData; // getter/setter @Action(value = "getResults", results = { @Result(name = SUCCESS, type = "json", params = { "root", "resultData", "enableGZIP", "true" }) }) public String execute() { // 初始化和赋值逻辑 return SUCCESS; } }
4. 调试输出中间结果
赋值完成后,直接打印服务器端的对象内容(手动转成JSON字符串),确认是否已经包含5组值,这样能区分是赋值逻辑问题还是序列化问题:
ObjectMapper mapper = new ObjectMapper(); System.out.println(mapper.writeValueAsString(resultData));
如果打印的JSON只有最后一组值,那肯定是赋值逻辑错了;如果打印的是正确的5组值,那就是Struts-JSON的配置问题。
内容的提问来源于stack exchange,提问作者Daler
相关产品推荐
相关产品推荐

