JSON to Apex Converter
Paste valid JSON below and the corresponding Apex will be generated. If any of your JSON keys would result in invalid Apex, such as reserved keywords, a custom parser will be generated.
public class GeneratedApex {
public UserProfile userProfile;
public class UserProfile {
public Integer userId; // 1001
public PersonalInfo personalInfo;
public Contact contact;
public Address address;
public List<SocialMediaProfiles> socialMediaProfiles;
}
public class PersonalInfo {
public String firstName; // "Jane"
public String lastName; // "Doe"
public Integer age; // 28
}
public class Contact {
public String email; // "jane.doe@example.com"
public Phone phone;
}
public class Phone {
public String home; // "555-1234"
public String work; // "555-5678"
}
public class Address {
public String street; // "123 Main St"
public String city; // "Springfield"
public String state; // "IL"
public String postalCode; // "62701"
}
public class SocialMediaProfiles {
public String platform; // "Twitter"
public String username; // "janedoe"
}
public static GeneratedApex parse(String jsonString) {
return (GeneratedApex) JSON.deserialize(jsonString, GeneratedApex.class);
}
}
How to Use the JSON to Apex Converter
Start by pasting your JSON data into the textarea on the left. The tool parses the JSON and generates corresponding Apex classes, which are displayed in the textarea on the right. These classes represent the structure of the JSON data, including nested objects and arrays, in a format compatible with Salesforce's Apex programming language. Sometimes, JSON payload properties use keywords reserved by Apex. In this case, a custom parser is generated because direct deserialization isn't possible. In either case, you simply need to pass the GeneratedApex.parse() method a valid JSON string to generate the corresponding Apex structure.
How to Use the Generated Apex
Generating Apex is one thing; knowing how to use it is another. Let's take a look at two examples. We begin with the simpler use case where the following JSON generates an Apex class that can be deserialized directly:
JSON
{
"userProfile": {
"userId": 1001,
"personalInfo": {
"firstName": "Jane",
"lastName": "Doe",
"age": 28
},
"contact": {
"email": "jane.doe@example.com",
"phone": {
"home": "555-1234",
"work": "555-5678"
}
},
"address": {
"street": "123 Main St",
"city": "Springfield",
"state": "IL",
"postalCode": "62701"
},
"socialMediaProfiles": [
{
"platform": "Twitter",
"username": "janedoe"
},
{
"platform": "LinkedIn",
"url": "https://www.linkedin.com/in/janedoe/"
}
]
}
}
Generated Apex
public class GeneratedApex {
public UserProfile userProfile;
public class UserProfile {
public Integer userId; // 1001
public PersonalInfo personalInfo;
public Contact contact;
public Address address;
public List<SocialMediaProfiles> socialMediaProfiles;
}
public class PersonalInfo {
public String firstName; // "Jane"
public String lastName; // "Doe"
public Integer age; // 28
}
public class Contact {
public String email; // "jane.doe@example.com"
public Phone phone;
}
public class Phone {
public String home; // "555-1234"
public String work; // "555-5678"
}
public class Address {
public String street; // "123 Main St"
public String city; // "Springfield"
public String state; // "IL"
public String postalCode; // "62701"
}
public class SocialMediaProfiles {
public String platform; // "Twitter"
public String username; // "janedoe"
}
public static GeneratedApex parse(String jsonString) {
return (GeneratedApex) JSON.deserialize(jsonString, GeneratedApex.class);
}
}
Using the generated class to deserialize the incoming JSON payload is simple once we have the structure in place. Below, you'll find a fully-fledged example of calling an API and then deserializing the JSON response. The deserialization is just one line of code.
public class ApiService {
public static GeneratedApex fetchUserData() {
// Create an HTTP request and response
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://api.example.com/userdata'); // Replace with your API endpoint
request.setMethod('GET');
request.setHeader('Content-Type', 'application/json');
try {
// Send the HTTP request and get the response
HttpResponse response = http.send(request);
// Check if the request was successful
if (response.getStatusCode() == 200) {
// Deserialize the JSON response into the GeneratedApex object
GeneratedApex result = (GeneratedApex) JSON.deserialize(response.getBody(), GeneratedApex.class);
return result;
} else {
// Handle the error scenario
System.debug('Error: ' + response.getStatusCode() + ' - ' + response.getStatus());
return null;
}
} catch (Exception e) {
// Handle any exceptions that occur during the HTTP request
System.debug('Exception: ' + e.getMessage());
return null;
}
}
}
The example above is straightforward and doesn't require a custom parser. However, if the generated Apex contains a reserved keyword or invalid character, a custom parser is required. That's the subject of the next section.
Deserializing JSON with a Custom Parser
JSON is a collection of key-value pairs that can be nested. If any of these keys are an Apex reserved keyword or contain invalid characters, such as starting with an underscore, then Apex generated using the above method will not compile.
Our converter detects such issues and automatically generates Apex code that includes a custom parser instead. Below is an example where JSON key names that would have caused issues in Apex are sanitized with namespace prefixes NS_ and ns.
JSON
{
"user": {
"userId": "user_456",
"email": "user@example.com",
"log-id": "abc123",
"_object": "accountActivation"
}
}
Generated Apex
public class GeneratedApex {
public NS_User nsUser;
public class NS_User {
public String userid;
public String email;
public String logid;
public String nsObject;
}
public static GeneratedApex parse(String jsonString) {
JSONParser parser = JSON.createParser(jsonString);
if (parser.nextToken() != null) {
return parseGeneratedApex(parser);
} else {
return null;
}
}
private static GeneratedApex parseGeneratedApex(JSONParser parser) {
GeneratedApex obj = new GeneratedApex();
while (parser.nextToken() != System.JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
String fieldName = parser.getText();
if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
if (fieldName == 'user') {
obj.nsUser = parseNS_User(parser);
} else {
System.debug(LoggingLevel.WARN, 'Unknown field: ' + fieldName);
consumeObject(parser);
}
}
}
}
return obj;
}
private static NS_User parseNS_User(JSONParser parser) {
NS_User obj = new NS_User();
while (parser.nextToken() != System.JSONToken.END_OBJECT) {
if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
String fieldName = parser.getText();
if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
if (fieldName == 'userId') {
obj.userid = parser.getText();
} else if (fieldName == 'email') {
obj.email = parser.getText();
} else if (fieldName == 'log-id') {
obj.logid = parser.getText();
} else if (fieldName == '_object') {
obj.nsObject = parser.getText();
} else {
System.debug(LoggingLevel.WARN, 'Unknown field: ' + fieldName);
consumeObject(parser);
}
}
}
}
return obj;
}
private static void consumeObject(JSONParser parser) {
Integer depth = 0;
do {
System.JSONToken curr = parser.getCurrentToken();
if (curr == System.JSONToken.START_OBJECT || curr == System.JSONToken.START_ARRAY) {
depth++;
} else if (curr == System.JSONToken.END_OBJECT || curr == System.JSONToken.END_ARRAY) {
depth--;
}
} while (depth > 0 && parser.nextToken() != null);
}
}
The generated Apex tends to be longer as there is more work involved in translating the JSON into Apex, but you would use it in much the same way as the example above.
public class ApiService {
// Method to fetch and parse JSON from the API
public static GeneratedApex fetchAndParseUser(String endpointUrl) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint(endpointUrl);
request.setMethod('GET');
try {
HttpResponse response = http.send(request);
if (response.getStatusCode() == 200) {
String jsonResponse = response.getBody();
System.debug('API Response: ' + jsonResponse);
// Deserialize JSON using GeneratedApex class
GeneratedApex parsedData = GeneratedApex.parse(jsonResponse);
System.debug('Parsed Data: ' + parsedData);
return parsedData;
} else {
System.debug('Error: HTTP response code ' + response.getStatusCode());
return null;
}
} catch (Exception e) {
System.debug('Error in API call: ' + e.getMessage());
return null;
}
}
}
References
- Apex Reference Guide: JSON Class