如何在 Salesforce Visualforce 页面中显示 JSON 数据?

How can I display JSON data in a Salesforce Visualforce Page?

编辑: 这是我对标注的想法:

public class APISocieteCallout {

String searchContent= //Content of the search
String apiKey= 'XXXXXXXXXXXXXXXXXXXXXX';
String requestEndpoint += 'https://api.societe.com/pro/dev/societe/';
requestEndpoint += 'search?nom=';
requestEndpoint += '&token='+apiKey;
requestEndpoint += '&format=json';

public static HttpResponse getSocieteInfo(){
Http http = new Http();
HttpRequest request = new HttpRequest();
requestEndpoint= 'https://api.societe.com/pro/dev/societe/';
request.setMethod('GET');


HttpResponse response = http.send(request);
System.debug(response.getStatusCode());

if(response.getStatusCode() == 200){
   Map<String,Object> result = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
   System.debug(result);
               
}

return response;

} }

抱歉,我是新手,无法获得不同的文档来帮助...

非常感谢, H.

一种方法是使用这些字段(public Integer n; public String siren; 等)创建一些助手 class 并将 JSON 反序列化为适当的顶点对象。或者直接将它作为字符串变量直接传递给 Visualforce,并在 JavaScript 中对其进行处理。取决于您认为什么更清洁以及您打算如何处理这些数据。对于只显示在 1 个 VF 页面上正确解析有点矫枉过正,但如果有其他东西可以使用它或 JavaScript 不是一个选项(例如 VF 页面呈现为 pdf ......)。另一方面,如果您要制作 Lightning Web 组件 - 没有必要浪费时间解析它,请按原样将其传递给 JS。

您不必手动创建辅助包装器 class。您可以将 JSON 文档提供给 https://json2apex.herokuapp.com/,它会为您生成 class 和解析代码,它会尝试猜测字段类型,甚至会绕过保留关键字(例如如果您的文件有“限制”或“触发”,则必须以特殊方式对其进行解析)。它甚至会包括最佳猜测单元测试,因此您要做的工作会少一些。

//
// Generated by JSON2Apex http://json2apex.herokuapp.com/
//

public class Wrapper{

    public Integer nb;
    public List<Result> result;

    public class Result {
        public Integer n;
        public String siren;
        public String ape;
        public String apetexte;
        public String rs;
        public String cp;
    }

    
    public static Wrapper parse(String json) {
        return (Wrapper) System.JSON.deserialize(json, Wrapper.class);
    }
}

这几乎是完美的。要在 VF 页面上使用,您需要添加 public Integer n {get;private set;} 或类似内容。

最后 - <apex:repeat>, <apex:pageBlockTable> 等标签循环遍历 {!wrapper.result}

编辑:代码转储:)

public class Stack72189633{

    static final String APIKEY = 'XXXXXXXXXXXXXXXXXXXXXX';
    static final String ENDPOINT = 'https://api.societe.com/pro/dev/societe/';
    
    public String searchTerm {get;set;}
    public Wrapper myData {get; private set;}
    
    // If the constructor can be empty we can skip it completely, SF will generate one for us silently
    //public Stack72189633(ApexPages.StandardController sc){}
    
    public void doSearch(){
        if(String.isBlank(searchTerm)){
            ApexPages.addMessage(new ApexPages.Message(ApexPages.Severity.ERROR, 'Nice try'));
            return;
        }
        
        if(searchTerm == 'fake'){
            String json = '{'+
            '\"nb\": 192,'+
            '\"result\": ['+
            '    {'+
            '        \"n\": 1,'+
            '        \"siren\": \"390206357\",'+
            '        \"ape\": \"9312Z\",'+
            '        \"apetexte\": \"XXXXXXXXXXXXXXXXXXXXXXXXXXXX\",'+
            '        \"rs\": \"AMICALE SORTIVE CULTURELLE DE LA BNP\",'+
            '        \"cp\": \"XXXXXXXXXXXX\"'+
            '    },'+
            '    {'+
            '        \"n\": 2,'+
            '        \"siren\": \"434285359\",'+
            '        \"ape\": \"9499Z\",'+
            '        \"apetexte\": \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",'+
            '        \"rs\": \"AMICALE DES RETRAITES BNP PARIBAS\",'+
            '        \"cp\": \"XXXXXXXXXXXXX\"'+
            '    },'+
            '    {'+
            '        \"n\": 3,'+
            '        \"siren\": \"524769841\",'+
            '        \"ape\": \"9499Z\",'+
            '        \"apetexte\": \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",'+
            '        \"rs\": \"AMICALE SPORTIVE ET CULTURELLE DE BNP\",'+
            '        \"cp\": \"XXXXXXXXXXXXX\"'+
            '    },'+
            '    {'+
            '        \"n\": 4,'+
            '        \"siren\": \"517815544\",'+
            '        \"ape\": \"XXXXX\",'+
            '        \"apetexte\": \"Activités de clubs de sports\",'+
            '        \"rs\": \"XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX\",'+
            '        \"cp\": \"05000 GAP\"'+
            '    }'+
            ']'+
            '}';
            myData = (Wrapper) System.JSON.deserialize(json, Wrapper.class);
        } else {

            // This is bit better than joining strings manually because it should urlencode special characters too.
            PageReference pr = new PageReference(ENDPOINT + 'search');
            pr.getParameters().putAll(new Map<String, String>{
                'nom' => searchTerm,
                'token' => APIKEY,
                'format' => 'json'
            });
            
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setMethod('GET');
            req.setEndpoint(pr.getUrl());
            
            HttpResponse res = new Http().send(req);
            if(res.getStatusCode() == 200 && String.isNotBlank(res.getBody())){
                myData = (Wrapper) System.JSON.deserialize(res.getBody(), Wrapper.class);
            }
        }
    }
    
    public class Wrapper{
        public Integer nb {get; private set;}
        public List<Result> result {get; private set;}
    }
    public class Result {
        public Integer n {get; private set;}
        public String siren {get; private set;}
        public String ape {get; private set;}
        public String apetexte {get; private set;}
        public String rs {get; private set;}
        public String cp {get; private set;}
    }
}
<apex:page controller="Stack72189633">
<apex:pageMessages />
<apex:form>
<apex:pageBlock title="Search form">
    <apex:pageBlockButtons location="bottom">
        <apex:commandButton value="Search" action="{!doSearch}" />
    </apex:pageBlockButtons>
    <apex:pageBlockSection>
        <apex:inputText label="Name" value="{!searchTerm}" required="true" />
    </apex:pageBlockSection>
</apex:pageBlock>
</apex:form>

<apex:pageBlock title="Results">
    <apex:pageBlockTable value="{!myData.result}" var="r" rendered="{!myData != null}">
        <apex:column headerValue="#" value="{!r.n}" />
        <apex:column headerValue="Siren" value="{!r.siren}" />
        <apex:column headerValue="APE" value="{!r.ape}" />
        <apex:column headerValue="Text" value="{!r.apetexte}" />
    </apex:pageBlockTable>
</apex:pageBlock>
</apex:page>