PrimeVue DataTable空行问题:如何将无键JSON转为标准带键格式
修复PrimeVue DataTable空行问题:后端JSON格式修正方案
后端修正步骤
1. 对齐实体类与前端字段需求
检查你的AgentServ实体类,必须包含id、fullName、acs、nom_service这几个字段,还要配上对应的getter方法——Jackson序列化依赖这些getter识别字段,否则无法生成带键的JSON:
public class AgentServ { private Long id; private String fullName; private String acs; private String nom_service; // 带参构造方法,用于映射数据库查询结果 public AgentServ(Long id, String fullName, String acs, String nom_service) { this.id = id; this.fullName = fullName; this.acs = acs; this.nom_service = nom_service; } // 必须的Getter方法 public Long getId() { return id; } public String getFullName() { return fullName; } public String getAcs() { return acs; } public String getNom_service() { return nom_service; } }
2. 修改DAO查询逻辑,返回实体对象列表
之前DAO大概率直接返回List<Object[]>这种嵌套数组,得改成把查询结果映射到AgentServ对象上:
// 示例DAO查询方法(以JdbcTemplate为例) public List<AgentServ> getAllAgents() { String sql = "SELECT id, full_name, acs, nom_service FROM agents"; return jdbcTemplate.query(sql, (rs, rowNum) -> new AgentServ( rs.getLong("id"), rs.getString("full_name"), rs.getString("acs"), rs.getString("nom_service") ) ); }
3. REST接口直接返回实体列表
Spring MVC会自动将List<AgentServ>序列化为符合要求的JSON对象数组,接口无需额外处理:
@GetMapping("/agents") public ResponseEntity<List<AgentServ>> getAgents() { List<AgentServ> agents = agentDao.getAllAgents(); return ResponseEntity.ok(agents); }
修正后后端返回的JSON格式会变成这样,完全匹配前端需求:
[ {"id": 1, "fullName": "张三", "acs": "ACS001", "nom_service": "技术部"}, {"id": 2, "fullName": "李四", "acs": "ACS002", "nom_service": "财务部"} ]
前端验证
确保Vue中DataTable的列field属性和后端返回的键完全对应(注意驼峰与下划线的区别,比如后端的nom_service直接对应前端field="nom_service"):
<DataTable :value="agents"> <Column field="id" header="ID"></Column> <Column field="fullName" header="姓名"></Column> <Column field="acs" header="ACS编号"></Column> <Column field="nom_service" header="部门"></Column> </DataTable> <script setup> import { ref, onMounted } from 'vue'; import axios from 'axios'; const agents = ref([]); onMounted(async () => { const res = await axios.get('/api/agents'); agents.value = res.data; }); </script>
内容的提问来源于stack exchange,提问作者jpvandekerkhove
相关产品推荐
相关产品推荐

