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": "[email protected]",
"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[] {'[email protected]'};
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.