JSON to Apex Converter
Paste valid JSON below and the corresponding Apex will be generated. If the generated Apex uses reserved keywords, you can use the alternative approach outlined below.
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 side. 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 any nested objects and arrays, in a format compatible with Salesforce's Apex programming language. Sometimes the JSON payload, and corresponding Apex use keywords reserved by the Apex programming language - these are flagged in the generated apex. Reserved keywords in JSON payloads require special treatement and your options are:
- Use JSON.deserializeUntyped() to deserialise the JSON into a nested collection of Map<String, Object>.
- Change the JSON delivered from the endpoint (not always possible).
- Do a search and replace on the payload deserialising it into the Apex classes (not recommended).
How to use the generated Apex
Generating Apex is one thing, but know how to use it is another. Let's take a look at an example. We begin with the following JSON and corresponding Apex:
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 deserialise 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 deserialising the JSON response. The deserialisation is just one line of code though.
public class ApiService {
public static GeneratedClass 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 GeneratedClass object
GeneratedClass result = (GeneratedClass) JSON.deserialize(response.getBody(), GeneratedClass.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 has an issue though. The generated Apex uses a reserved keyword so the Apex compiler allow the generated Apex to be saved to the server. What's the best way to deal with payloads that use reserved keywords? That's the subject of the next section.
Deserialising JSON without Custom Apex Classes
JSON is simply a collection of key-value pairs that can be nested. Values can either be primitive types, other JSON objects (key-value pairs), or arrays. Because of this we can parse JSON into a nested collection of Map<String, Object> variables. The below code will parse any JSON into such a structure.
// You could wrap this method in a utility class
public static Map<String, Object> parse(String jsonString) {
return (Map<String, Object>) System.JSON.deserializeUntyped(jsonString);
}
// Example Usage
String json = '{"result":[{"status":"active","name":{"first":"Jada","middle":"Skyler","last":"Lynch"},"username":"Jada-Lynch","password":"Gllab7ROhZnh_u5","emails":["Doyle.Kovacek@gmail.com","Terrence.Klein93@gmail.com"],"phoneNumber":"612-956-1190 x03300","location":{"street":"46295 Delores Union","city":"East Geraldfurt","state":"South Dakota","country":"Chile","zip":"27547","coordinates":{"latitude":59.7505,"longitude":-121.3076}},"website":"https://glittering-asymmetry.biz/","domain":"dapper-nectarine.biz","job":{"title":"District Implementation Executive","descriptor":"Investor","area":"Identity","type":"Engineer","company":"Schmitt Inc"},"creditCard":{"number":"3529-8137-3548-7847","cvv":"703","issuer":"jcb"},"uuid":"b43ddb16-46c3-4145-b85a-4c580d6e4e03","objectId":"66a23ba9cabe594edc8a7f5b"},{...}]}';
Map<String, Object> deserializedJson = parse(json);
// Accessing top-level properties
List<Object> resultList = (List<Object>) deserializedJson.get('result');
// Iterating over the array of results
for (Object resultObj : resultList) {
Map<String, Object> result = (Map<String, Object>) resultObj;
// Accessing properties at the second level
String status = (String) result.get('status');
Map<String, Object> name = (Map<String, Object>) result.get('name');
String firstName = (String) name.get('first');
String lastName = (String) name.get('last');
// Accessing properties inside nested objects
Map<String, Object> location = (Map<String, Object>) result.get('location');
String city = (String) location.get('city');
Map<String, Object> coordinates = (Map<String, Object>) location.get('coordinates');
Double latitude = (Double) coordinates.get('latitude');
// Accessing an array of objects
List<Object> emails = (List<Object>) result.get('emails');
for (Object emailObj : emails) {
String email = (String) emailObj;
System.debug('Email: ' + email);
}
// Debug outputs
System.debug('Status: ' + status);
System.debug('First Name: ' + firstName);
System.debug('Last Name: ' + lastName);
System.debug('City: ' + city);
System.debug('Latitude: ' + latitude);
}
// Reserialize the Apex data structure as a test
System.debug(System.JSON.serialize(deserializedJson));
The key advantage with this approach is that your JSON can include reserved Apex keywords. The key disadvantage is having to step through the nested Map<String,Object> structure to access particular JSON properties.
References
- Apex Reference Guide: JSON Class