本文介绍了一个在Salesforce Apex中使用JSON数据的示例程序, 该示例程序由如下几部分组成:json
1) Album.cls
, 定了了封装相关字段的数据Model类
2) RestClient.cls
,实现了一个REST服务的客户端, 将REST服务返回的JSON数据转换为Album
的列表
3) AlbumController.cls
,实现了一个Salesforce的Controller, 将Album列表提供给UI页面
4) AlbumList.page
,实现了一个Salesforce的UI页面, 显示Album列表数据结构
public class Album { public Integer id { get; set; } public String title { get; set; } }
该Model类包含两个字段, id
和title
。ide
public class RestClient { public List<Album> getAlbums() { //build request String baseURL = 'http://jsonplaceholder.typicode.com/albums/'; HttpRequest req = new HttpRequest(); req.setEndpoint(baseURL); req.setMethod('GET'); //call REST server Http http = new Http(); HttpResponse res = http.send(req); String response = res.getBody(); System.debug('Rest Service Response: ' + response); //Convert REST response JSON to object List<Object> objects = (List<Object>) JSON.deserializeUntyped(response); List<Album> albums = new List<Album>(); for(Object theObject : objects) { Map<String, Object> albumJSONObject = (Map<String, Object>) theObject; Album theAlbum = new Album(); theAlbum.id = (Integer) albumJSONObject.get('id'); theAlbum.title = (String) albumJSONObject.get('title'); albums.add(theAlbum); } return albums; } }
以上代码首先使用http://jsonplaceholder.typicode.com/albums/
提供的REST服务, 该服务放回以下的JSON数据。函数
[ { "userId": 1, "id": 1, "title": "quidem molestiae enim" }, { "userId": 1, "id": 2, "title": "sunt qui excepturi placeat culpa" }, { "userId": 1, "id": 3, "title": "omnis laborum odio" }, { "userId": 1, "id": 4, "title": "non esse culpa molestiae omnis sed optio" }, { "userId": 1, "id": 5, "title": "eaque aut omnis a" }, { "userId": 1, "id": 6, "title": "natus impedit quibusdam illo est" }, { "userId": 1, "id": 7, "title": "quibusdam autem aliquid et et quia" }, ... ]
而后使用Apex提供的JSON.deserializeUntyped
方法将JSON数据转换为一个Map<String, Object>
, 接着根据JSON数据结构依次构造Album
对象并加入列表之中。jsonp
最后返回Album
对象列表。ui
public class AlbumController { public List<Album> albums {get;set;} public AlbumController () { RestClient client = new RestClient(); albums = new List<Album>(); albums.addAll(client.getAlbums()); } }
<apex:page controller="AlbumController" showChat="false" showHeader="false"> <apex:pageBlock title="Albums" > <apex:pageblocktable value="{!albums}" var="album"> <apex:column headervalue="Id" value="{!album.id}"/> <apex:column headervalue="Title" value="{!album.title}"/> </apex:pageblocktable> </apex:pageBlock>> </apex:page>
AlbumController
和AlbumList
的实现十分简单, AlbumController
在其构造函数中调用RestClient
以获取Album列表,AlbumList
则使用一个pageblocktable
组件来显示Album的信息。debug