SOQLクエリの結果をJSONで出力する
SOQLで取得したクエリ内容をJSONにパースして出力する方法。
Apexクラス
public class sample
{
public String text1 {get;set;}
public sample()
{
}
public void parseJson()
{
String soql = 'SELECT Name FROM Lead';
List<Account> acct = Database.Query(soql);
text1 = JSON.serialize(acct);
}
}
VisualForceページ
<apex:page showHeader="false" controller="ShowCampaignListController" action="{!parseJson}">
{!text1}
</apex:page>
出力結果例
[{
"attributes":
{
"type":"Lead",
"url":"/services/data/v32.0/sobjects/Lead/00QO0000002xxxxxxx"
},
"Name":"テストユーザー3",
"Id":"00QO0000002xxxxxxx"
},
{
"attributes":
{
"type":"Lead",
"url":"/services/data/v32.0/sobjects/Lead/00QO0000002ooooooo"
},
"Name":"テストユーザー2",
"Id":"00QO0000002ooooooo"
}]
参考:Infallible Techie: Generating JSON in Visualforce page in Salesforce