0

I would like to replace my current code with the JSON2APEX classes generated however I am unsure how to do this. My current class:

public with sharing class LeadAPIHandler {

    // the Reed API handler
    @future (callout=true)
    public static void reedLeadAPIHandler() {

        // if we get an exception in the callout, or when trying to insert the leads, log the error.            
        try {                

            HttpResponse res = issueReedCallOut();
            system.debug(res.getBody());
            parseReedCalloutResponse(res);      
        } catch (Exception e) {
            // log exeption to error log 
        }  
    }

    public static void parseReedCalloutResponse(HttpResponse res) {

        /* Expecting a response in this format
            "totalItemCount": 8,
            "totalPages": 1,
            "leads": [
            { 
              "enquiryId": 1210063, 
              "courseId": 29346,
              "providerCourseRef": null,
              "createdOn": "2015-01-23T13:01:37",
              "firstName": "Christopher",
              "lastName": "Wright",
              "email": "amoskia@hotmail.com",
              "phone": "970569778406",
              "country": null,
              "postcode": null,
              "comment": null,
              "courseTitle": "BTEC Level 3 Certificate in Mechanical Engineering"
            }
            */

            // get the JSON response to parse
            JSONParser parser = JSON.createParser(res.getBody());
            List<Lead> parsedLeads = new List<Lead>();
            Lead l = null;    

            ID leadsQueue = [ SELECT queue.id FROM queuesobject WHERE queue.name='Inbound Leads'].queueid;
            integer totalLeadsReceived = 0;

            while (parser.nextToken() != null) {            
                    JSONToken token = parser.getCurrentToken();
                String value = parser.getText();
                system.debug('*** value ' + value);
                if(token == JSONToken.START_OBJECT) {
                    system.debug('*** creating new lead ');           
                    l = new Lead();             
                }   
                if(value == 'totalItemCount') {
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    totalLeadsReceived = parser.getIntegerValue();     
                }
                if(value == 'enquiryId') {          
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    l.Supplier_ID__c = parser.getText();                    
                }   
                if(value == 'courseId') {           
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    l.Supplier_Course_ID__c = parser.getText();                 
                }
                if(value == 'firstName') {          
                    parser.nextToken();     
                    parser.getCurrentToken();
                    system.debug('*** fn value ' + parser.getText());
                    l.FirstName = parser.getText();
                    l.LeadSource = 'Third Party';   
                    l.Supplier__c = 'Reed';
                    l.OwnerId = leadsQueue; 
                    l.Active_Lead__c = 'TRUE';                                                
                }   
                if(value == 'lastName') {
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    l.LastName = parser.getText();                              
                }   
                if(value == 'email') {          
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    l.Email = parser.getText();                 
                }    
                if(value == 'phone') {          
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    l.Phone = parser.getText();                 
                }        
                if(value == 'screeningQuestions') {
                    String questions = '';
                    while(parser.getText() != ']') {
                        parser.nextToken(); 
                        parser.getCurrentToken(); 
                        questions += parser.getText();
                    }
                    if(questions!='')
                        l.Notes__c = questions;
                }    
                if(value == 'course') {
                    while(parser.getText() != '}') {
                        parser.nextToken(); 
                        parser.getCurrentToken(); 
                        if(parser.getText() == 'awardingBody') {
                            parser.nextToken(); 
                            parser.getCurrentToken(); 
                            l.DistributionValue__c = 'REED ' + parser.getText(); 
                        }
                    }  
                }  
                if(value == 'site') {           
                    parser.nextToken();     
                    parser.getCurrentToken();           
                    String site = parser.getText();   
                    if(site=='Business') {
                        l.RecordTypeId = Schema.getGlobalDescribe().get('Lead').getDescribe().getRecordTypeInfosByName().get('Corporate').getRecordTypeId();         
                        // we want the company to be blank so the adviser has to capture it
                        l.company = 'Reed Default';    
                    }
                    else {
                        l.RecordTypeId = Schema.getGlobalDescribe().get('Lead').getDescribe().getRecordTypeInfosByName().get('Consumer').getRecordTypeId();
                        l.company = l.FirstName + ' ' + l.LastName;
                    }
                }  
                if(token == JSONToken.END_OBJECT && l != null && l.LastName != null) {   
                    system.debug('*** lead so far ' + l);                   
                    parsedLeads.add(l);
                    l = null;
                }
            }

            system.debug('** parsed leads ' + parsedLeads);

            // check if we have been unable to parse all of the leads. 
            // Email exception if total number parsed not equal to total number received.           
            if(parsedLeads.size() != totalLeadsReceived) {
                Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
                string[] to = new String[] {'it.support@icslearn.co.uk'};
                email.setToAddresses( to  );
                email.setSubject( 'ERROR: Reed API Lead Parsing Issues');
                email.setPlainTextBody('The Reed API has sent across ' + totalLeadsReceived +
                                        ' Leads, however only ' + parsedLeads.size() + 
                                        ' have been successfully parsed. \n' + 
                                        ' Please find the API response below and create Leads manually if required. \n\n' +
                                        res.getBody());                    
                // Send it
                Messaging.SendEmailResult [] r =
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
                System.debug(r.size());
                System.debug(r[0].success);       
                System.debug(r[0].getErrors());
            }

            // if we get some leads, check if they have been seen already today.        
            if(parsedLeads.size() > 0) {

                List<Lead> leadsToInsert = new List<Lead>();
                List<Lead> leadsReceivedAlready = [ SELECT id, Supplier_ID__c, createdDate FROM Lead WHERE Supplier__c = 'Reed' AND createdDate = TODAY ];
                Set<String> leadIDSReceivedAlready = new Set<String>();
                for(Lead receivedLead : leadsReceivedAlready) 
                    if(!leadIDSReceivedAlready.contains(receivedLead.Supplier_ID__c))
                        leadIDSReceivedAlready.add(receivedLead.Supplier_ID__c);

                system.debug('*** lead ids received already ' + leadIDSReceivedAlready);

                for(Lead parsedLead : parsedLeads) 
                    if(!leadIDSReceivedAlready.contains(parsedLead.Supplier_ID__c))
                        leadsToInsert.add(parsedLead);                      

                // if not seen, insert them
                if(leadsToInsert.size()>0)   
                    insert leadsToInsert;       
            }               
    }

    public static HttpResponse issueReedCallout() {

        // create a call out to the Reed API. Get tthe endpoint and apikey from the custom setting.        
        Http h = new Http(); 
        HttpResponse res = new HttpResponse();
        HttpRequest req = new HttpRequest();
        ReedAPIConfig__c config = ReedAPIConfig__c.getValues('current');
        if(config != null) {            
            req.setEndpoint(config.Endpoint__c);
            req.setMethod('GET');        
            String apikey = config.Apikey__c;
            String password = '';
            Blob headerValue = Blob.valueOf(apikey + ':' + password);
            String authorizationHeader = 'BASIC ' +
            EncodingUtil.base64Encode(headerValue);
            req.setHeader('Authorization', authorizationHeader);
            req.setHeader('Accept', 'application/json');

            system.debug('req' + req);
            res = h.send(req);            
        }
        return res;
    }
}

The classes produced by APEX2JSON

public class ReedAPIHandler {

    public class ReedAPIResponse {
        public Integer totalItemCount;
        public Integer totalPages;
        public List<Leads> leads;
        public List<Links> links;
    }

    public class ScreeningQuestions {
        public String question;
        public String answer;
        public String expectedAnswer;
    }

    public class Course_Z {
        public Integer courseId;
        public String title;
        public Object providerCourseRef;
        public String qualification;
        public String awardingBody;
    }

    public class Leads {
        public Integer enquiryId;
        public Integer courseId;
        public String providerCourseRef;
        public String createdOn;
        public String firstName;
        public String lastName;
        public String email;
        public String phone;
        public Object country;
        public Object postcode;
        public Object comment;
        public String courseTitle;
        public Object employmentStatus;
        public Object contactTime;
        public Object startAvailibility;
        public List<ScreeningQuestions> screeningQuestions;
        public Course course;
        public String site;
        public Object companyName;
        public Object companyJobTitle;
        public Object companySize;
    }

    public class Links {
        public String href;
        public String rel;
        public String method;
    }

    public class Course {
        public Integer courseId;
        public String title;
        public String providerCourseRef;
        public String qualification;
        public String awardingBody;
    }

    public class ScreeningQuestions_Z {
    }


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

}

Any help with this would be appreciated.

3 Answers 3

2

It would be easier to just use JSON.serialize and JSON.deserialize directly with the Apex classes, like this:

ReedAPIHandler.ReedAPIResponse resp = (ReedAPIHandler.ReedAPIResponse) JSON.deserialize(inboundJsonBody, ReedAPIHandler.ReedAPIResponse.class);
for (ReedAPIHandler.Leads reedLead : resp.leads) {
    Lead theLead = new Lead();
    theLead.FirstName = reedLead.lastName;
    etc...
}
3
  • Thanks for this David. I get an error with this: Variable does not exist: inboundJsonBody - should I be changing this? I have tried to add 'res' as the actual JSON response however I get this error: Method does not exist or incorrect signature: void deserialize(System.HttpResponse, System.Type) from the type System.JSON
    – Hannah
    Nov 27, 2017 at 9:40
  • inboundJsonBody was merely an example variable, you need to replace it with whatever your HTTP response body is. Nov 27, 2017 at 15:02
  • Thanks David. I have this working now. I am just looking at my test class now.
    – Hannah
    Nov 30, 2017 at 11:34
0

If you have used http://json2apex.herokuapp.com/ to generate the Class, it has created a test class for you. You can check the bottom of the Test class to see how to use it. The last two lines should look like this.

List<JSON2Apex> obj = JSON2Apex.parse(json);
System.assert(obj != null);
1
  • Thanks Saroj, I have the test class however I am still not sure how I replace the JSON in my current class with the JSON2APEX class. I have tried to add a for loop at JSONParser parser = JSON.createParser(res.getBody()); line in my code to replace it however this did not work.
    – Hannah
    Nov 23, 2017 at 11:10
-1

Try using like this :--`

public List<ReedAPIHandler > listofvalue {get;set;}


if(res.getStatusCode() == 200){
                      String jsonString = res.getBody();
                      System.debug( 'jsonString:::-->>>' + jsonString);
                      if(!String.isEmpty(jsonString)){
                          listofvalue = (List<ReedAPIHandler>)JSON.deserialize(jsonString, List<ReedAPIHandler>.class);

                      }


     }`
1
  • this won't work as the response is most likely not a list given the generated class
    – Eric
    Nov 25, 2017 at 0:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.