【问题标题】:Parsing json in apex在 apex 中解析 json
【发布时间】:2017-07-03 12:47:25
【问题描述】:

您好,我创建了一个 RESTful Web 服务,它以以下格式返回响应:

[
{"empId":1,"empName":"A"},
{"empId":2,"empName":"B"},
{"empId":3,"empName":"C"},
{"empId":4,"empName":"D"},
{"empId":5,"empName":"E"}
]

我已经编写了简单的 visualforce 页面来在按钮单击操作上调用名为“lookup”的方法。我的 Apex 课程如下所示。

public class REST {
  public PageReference lookup()
  {
    string resp;

    // Note this version of the API is only for the US
    string endpoint ='http://localhost:8080/RESTfulExample/rest/json/metallica/get';

    HttpRequest req = new HttpRequest();
    HttpResponse res = new HttpResponse();
    Http http = new Http();
    req.setMethod('GET');
    req.setEndpoint(endpoint);

    try {
      res = http.send(req);
    } catch (Exception e) {
      system.debug(LoggingLevel.Error, 'Error HTTP response code = '+res.getStatusCode()+'; calling '+endpoint );
      return null;
    }

    resp = res.getBody();
    JSONParser parser = JSON.createParser(resp);

    // Parsing The JSON & set the list of values to the variables 'empid' & 'empname'

    return null;
  }
}

谁能帮助我如何使用 JSON 解析器来解析 JSON 并将值存储到变量中。

谢谢你!!!

【问题讨论】:

    标签: json apex-code


    【解决方案1】:

    如果您想使用 JSONParser,这里是 Salesforce 文档中关于 JSONParser(https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_json_jsonparser.htm) 的示例:

    public class JSONParserUtil {
        @future(callout=true)
        public static void parseJSONResponse() {        
            Http httpProtocol = new Http();
            // Create HTTP request to send.
            HttpRequest request = new HttpRequest();
            // Set the endpoint URL.
            String endpoint = 'https://docsample.herokuapp.com/jsonSample';
            request.setEndPoint(endpoint);
            // Set the HTTP verb to GET.
            request.setMethod('GET');
            // Send the HTTP request and get the response.
            // The response is in JSON format.
            HttpResponse response = httpProtocol.send(request);
            System.debug(response.getBody());
            /* The JSON response returned is the following:
            String s = '{"invoiceList":[' +
            '{"totalPrice":5.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
                '{"UnitPrice":1.0,"Quantity":5.0,"ProductName":"Pencil"},' +
                '{"UnitPrice":0.5,"Quantity":1.0,"ProductName":"Eraser"}],' +
                    '"invoiceNumber":1},' +
            '{"totalPrice":11.5,"statementDate":"2011-10-04T16:58:54.858Z","lineItems":[' +
                '{"UnitPrice":6.0,"Quantity":1.0,"ProductName":"Notebook"},' +
                '{"UnitPrice":2.5,"Quantity":1.0,"ProductName":"Ruler"},' +
                '{"UnitPrice":1.5,"Quantity":2.0,"ProductName":"Pen"}],"invoiceNumber":2}' +
            ']}'; 
            */
    
            // Parse JSON response to get all the totalPrice field values.
            JSONParser parser = JSON.createParser(response.getBody());
            Double grandTotal = 0.0;
            while (parser.nextToken() != null) {
                if ((parser.getCurrentToken() == JSONToken.FIELD_NAME) && 
                    (parser.getText() == 'totalPrice')) {
                    // Get the value.
                    parser.nextToken();
                    // Compute the grand total price for all invoices.
                    grandTotal += parser.getDoubleValue();
                }
            }
            system.debug('Grand total=' + grandTotal);
        }   
    }
    

    尽管从您在问题中所说的内容来看,我认为进行 JSON 反序列化会更简单。

    下面是一个例子:

    包装类

    public class EmployeeWrapper {
        public Integer empId {get;set;}
        public String empName {get;set;}
    }
    

    JSON 反序列化

    String jsonContent = '[{"empId": 1,"empName": "A"}, {"empId": 2,"empName": "B"}, {"empId": 3,"empName": "C"}, {"empId": 4,"empName": "D"}, {"empId": 5,"empName": "E"}]';
    List<EmployeeWrapper> employeeWrapperList = (List<EmployeeWrapper>)JSON.deserialize(jsonContent, List<EmployeeWrapper>.class);
    System.debug(employeeWrapperList);
    //Do actions to WrapperList
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-11
      • 1970-01-01
      相关资源
      最近更新 更多