本文介紹了一個在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