Question:
How to Customize an Apex Class for Including a JSON Payload in an HTTP Request POST Method?
I’m new to coding in Apex and JSON, and I want to customize my Apex class (generated from a JSON-to-Apex generator) to include a JSON payload in an HTTP POST Request. Here’s the generated Apex class:
public class httpCalloutJson {
public String CompanyCode;
public String WorkerName;
public String AccountNumber;
public Boolean UseWarrantyAccount;
public String ShippingWhs;
public Boolean FreightCovered;
public String CaseNumber;
public String ReferenceNumber;
public String WarrantyReason;
public String ContactName;
public String ContactEmail;
public String DlvAddressName;
public String DlvAddressStreet;
public String DlvAddressZipcode;
public String DlvAddressCity;
public String DlvAddressState;
public String DlvAddressCountry;
public String DlvNote;
public List<Lines> Lines;
public class Lines {
public String ItemNumber;
public Integer Quantity;
public String Unit;
public String Description;
public Integer DiscPercent;
}
public static httpCalloutJson parse(String jsonString) {
return (httpCalloutJson) JSON.deserialize(jsonString, httpCalloutJson.class);
}
}
I’m trying to use this class to send an HTTP POST request with the JSON payload. I’ve started writing the following code, but I’m confused about how to customize and complete it. Any guidance or corrections would be appreciated!
Answer
If you’re new to coding, specifically in Apex and working with JSON, you might be wondering how to integrate a generated JSON class into an HttpRequest
class when making a POST request. Let’s break down the process of how to do this, step-by-step.
When you generate a JSON class (using a JSON-to-Apex tool), you end up with a class that contains properties matching the keys in your JSON object. To use this class for an HTTP POST request, you need to first instantiate an object of that class, set its properties, and then serialize it into a JSON string. After this, you can set it as the body of your HTTP request.
Here’s how you can integrate the JSON class into your HTTP request:
1. Define the JSON Class
First, you need to define your JSON class. Here’s an example of the class generated from a JSON-to-Apex generator:
public class httpCalloutJson {
public String CompanyCode;
public String WorkerName;
public String AccountNumber;
public Boolean UseWarrantyAccount;
public String ShippingWhs;
public Boolean FreightCovered;
public String CaseNumber;
public String ReferenceNumber;
public String WarrantyReason;
public String ContactName;
public String ContactEmail;
public String DlvAddressName;
public String DlvAddressStreet;
public String DlvAddressZipcode;
public String DlvAddressCity;
public String DlvAddressState;
public String DlvAddressCountry;
public String DlvNote;
public List<Lines> Lines;
public class Lines {
public String ItemNumber;
public Integer Quantity;
public String Unit;
public String Description;
public Integer DiscPercent;
}
public static httpCalloutJson parse(String jsonString) {
return (httpCalloutJson) JSON.deserialize(jsonString, httpCalloutJson.class);
}
}
Code Explanation:
This snippet defines a class called httpCalloutJson
, which models the JSON structure. It contains properties corresponding to the JSON keys like CompanyCode
, WorkerName
, and Lines
. The Lines
class is defined within the parent class to hold item-specific details. The parse
method uses JSON.deserialize
to convert JSON data into an instance of this class.
2. Instantiate and Set Values
Next, you need to create an instance of this class and set its properties using dot-notation. This can be done like so:
public class HttpRequestSample {
public void makeHttpPostRequest() {
// Instantiate the JSON class
httpCalloutJson jsonPayload = new httpCalloutJson();
// Set the properties
jsonPayload.CompanyCode = '1700';
jsonPayload.WorkerName = 'Bailey1';
jsonPayload.AccountNumber = 'C0001';
jsonPayload.UseWarrantyAccount = true;
jsonPayload.ShippingWhs = '06';
jsonPayload.FreightCovered = true;
jsonPayload.CaseNumber = 'Case1';
jsonPayload.ReferenceNumber = 'PO-12345';
jsonPayload.WarrantyReason = 'Camo-Replacement';
jsonPayload.ContactName = 'Test Person';
jsonPayload.ContactEmail = 'test.person@company.com';
jsonPayload.DlvAddressName = 'Test Installer';
jsonPayload.DlvAddressStreet = 'Installerstreet 20';
jsonPayload.DlvAddressZipcode = '994455';
jsonPayload.DlvAddressCity = 'New York';
jsonPayload.DlvAddressState = 'NY';
jsonPayload.DlvAddressCountry = 'USA';
jsonPayload.DlvNote = 'Deliver add dock 22';
// Initialize the list of lines
jsonPayload.Lines = new List<httpCalloutJson.Lines>();
httpCalloutJson.Lines line1 = new httpCalloutJson.Lines();
line1.ItemNumber = 'CAMO-01-M1';
line1.Quantity = 100;
line1.Unit = 'EA';
line1.Description = 'Universal Clamp';
line1.DiscPercent = 100;
jsonPayload.Lines.add(line1);
// Serialize the object into JSON
String strJson = JSON.serialize(jsonPayload);
// Make the HTTP POST request
Http h = new Http();
HttpRequest req = new HttpRequest();
req.setEndpoint('callout:WarrantyIntegrationAPI');
req.setMethod('POST');
req.setHeader('Content-Type', 'application/json');
req.setBody(strJson);
// Send the request
HttpResponse res = h.send(req);
}
}
Code Explanation:
This code snippet creates an instance of the httpCalloutJson
class and sets values for its properties. It also initializes a list of Lines
and adds an item to the list. After setting all the values, the class is serialized into a JSON string using JSON.serialize
. Finally, an HttpRequest
is created, and the method setBody()
is used to send the serialized JSON as the body of the POST request. The request is then sent using the Http.send()
method.
3. Making the HTTP Request
After you’ve set up your JSON object and serialized it, you can create an HttpRequest
object and specify the POST
method. Then, use the setBody
method to send the serialized JSON data in the request body. Here’s how to do that in the HttpRequest
class:
By following this approach, you integrate the generated JSON class into your Apex code, serialize it, and use it in an HTTP POST request. The key steps are initializing the class, setting its values, serializing it into JSON, and then setting that JSON into the HTTP request body.
Summing Up
To use a JSON class in an Apex HTTP POST request, you first generate the class based on the expected JSON structure and instantiate it in your code. After setting the appropriate values for the class properties using dot-notation, you serialize the object into a JSON string with JSON.serialize()
. This serialized JSON is then set as the body of an HttpRequest
object using the setBody()
method, and the request is sent using the Http.send()
method. This process allows you to easily send structured JSON data in HTTP POST requests from Salesforce Apex, making it ideal for integration with external APIs.
Real-Time Project-Based Salesforce Course to Kick Start Your Career
Our Salesforce Course is designed to provide you with a comprehensive understanding of the Salesforce platform, enabling you to build a rewarding career in one of the world’s most popular CRM solutions. We cover key areas such as Salesforce Admin, Developer, and AI modules, with a strong focus on hands-on learning through real-time projects. This practical approach ensures that you not only grasp theoretical concepts but also gain the skills needed to solve real-world business challenges. Led by experienced trainers, our course ensures you’re fully prepared for the dynamic demands of the Salesforce ecosystem.
In addition to technical training, our Salesforce training in Hyderabad offers personalized mentorship, expert certification guidance, and interview preparation to help you stand out in the competitive job market. You’ll receive detailed study materials, engage in live project work, and get one-on-one support to fine-tune your skills. Our goal is to ensure you’re not just ready for a certification exam, but are equipped with the practical, job-ready skills that employers value. Join us and take the first step towards mastering Salesforce and advancing your career.