如何使用<apex:pageBlockTable>展示List<Map<String, Object>>类型的数据?
解决Visualforce中用
<apex:pageBlockTable>展示List<Map<String, Object>>数据的问题 我来帮你搞定这个问题~首先得明确一个关键点:<apex:outputField> 是专门用来绑定Salesforce标准/自定义对象字段的组件,它没办法直接处理Map<String, Object>里的普通值。我们可以换成<apex:outputText>或者直接用表达式取值,下面分两种场景给你具体方案:
场景1:已知要展示的字段名(静态列)
如果你的表头字段是固定的(比如示例里的id、name、description、address),直接修改Visualforce代码即可:
<apex:pageBlockTable value="{!theJsonMapList}" var="al"> <apex:column headerValue="id"> <apex:outputText value="{!al['id']}" /> </apex:column> <apex:column headerValue="name"> <apex:outputText value="{!al['name']}" /> </apex:column> <apex:column headerValue="description"> <apex:outputText value="{!al['description']}" /> </apex:column> <apex:column headerValue="address"> <apex:outputText value="{!al['address']}" /> </apex:column> </apex:pageBlockTable>
这里用{!al['keyName']}的语法直接从Map中取出对应的值,<apex:outputText>可以完美展示字符串、数字这类基本数据类型。
场景2:字段名/数量不固定(动态列)
你提到Map的数量是可变的,也就是表头字段可能不确定,这种情况我们需要先在Apex里提取所有唯一的字段名作为表头,再在Visualforce中动态渲染列:
第一步:修改Apex代码,新增表头属性
public List<Map<String, Object>> theJsonMapList {get; set;} public List<String> tableHeaders {get; set;} // 存储所有表头字段 // 解析JSON并提取表头的方法 public void parseJsonData() { String theJsonString = '[{"id":1, "name":"Abc_SS", "description":"Abc", "address":"Abc"}, {"id":2, "name":"sales", "description":"sales", "address":"Abc"}]'; Object theJsonObject = JSON.deserializeUntyped(theJsonString); List<Object> theJsonList = (List<Object>) theJsonObject; theJsonMapList = new List<Map<String, Object>>(); Set<String> headerSet = new Set<String>(); // 用Set自动去重 for (Object obj : theJsonList) { Map<String, Object> tempMap = (Map<String, Object>) obj; theJsonMapList.add(tempMap); headerSet.addAll(tempMap.keySet()); // 收集所有Map的Key } tableHeaders = new List<String>(headerSet); // 转成List供Visualforce遍历 }
第二步:修改Visualforce代码,动态生成列
<apex:pageBlockTable value="{!theJsonMapList}" var="al"> <apex:repeat value="{!tableHeaders}" var="header"> <apex:column headerValue="{!header}"> <apex:outputText value="{!al[header]}" /> </apex:column> </apex:repeat> </apex:pageBlockTable>
这里用<apex:repeat>遍历我们提前提取好的表头列表,自动创建对应数量的列,再通过{!al[header]}动态取出每个Map中对应字段的值,完全适配字段数量可变的场景。
小提示:如果你的Map值里包含嵌套的Map或List这类复杂类型,还需要额外处理嵌套结构的展示,但从你的示例JSON来看都是基本数据类型,上面的方案完全够用。
内容的提问来源于stack exchange,提问作者Rio Nish
相关产品推荐
相关产品推荐

