ScriptNCodeScriptNCode

Developer Blog

Insights, tutorials, and best practices from the Salesforce development community

All PostsTutorialsBest PracticesNewsCommunity
Back to Blog

Converting JSON to Apex Classes: A Complete Guide

S
ScriptNCode Team
8 min read

Converting JSON to Apex Classes: A Complete Guide

Converting JSON to Apex classes is a common task in Salesforce development, especially when working with external APIs. Our JSON to Apex converter makes this process seamless and efficient.

Understanding JSON to Apex Conversion

When working with external APIs in Salesforce, you need to:

  1. Parse incoming JSON data
  2. Convert it into Apex objects
  3. Handle the data in your business logic

Using the Converter

Step 1: Prepare Your JSON

Start with a valid JSON structure:

{
  "id": "12345",
  "name": "John Doe",
  "email": "john@example.com",
  "account": {
    "id": "ACC001",
    "type": "Premium",
    "status": "Active"
  },
  "orders": [
    {
      "orderId": "ORD-1",
      "amount": 100.50
    }
  ]
}

Step 2: Generate Apex Classes

Our tool will generate the following Apex classes:

public class Customer {
    public String id;
    public String name;
    public String email;
    public Account account;
    public List<Order> orders;
    
    public class Account {
        public String id;
        public String type;
        public String status;
    }
    
    public class Order {
        public String orderId;
        public Decimal amount;
    }
}

Best Practices

1. Handling Null Values

Always check for null values when deserializing:

try {
    Customer customer = (Customer)JSON.deserialize(jsonString, Customer.class);
    if (customer.orders == null) {
        customer.orders = new List<Order>();
    }
} catch(JSONException e) {
    // Handle exception
}

2. Custom Deserialization

For complex scenarios, implement custom deserialization:

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

Advanced Features

1. Handling Date Formats

Different APIs might use different date formats. Our converter handles common formats:

public class Event {
    public DateTime eventDate; // ISO format
    public Date startDate;    // YYYY-MM-DD
    public String timeZone;
}

2. Complex Nested Structures

Handle deeply nested JSON structures:

{
  "data": {
    "results": [
      {
        "records": [
          {
            // Deep nesting
          }
        ]
      }
    ]
  }
}

Testing Generated Classes

Always test your generated classes:

@isTest
private class CustomerTest {
    @isTest
    static void testDeserialization() {
        String json = '{"id":"12345","name":"Test"}';
        Customer customer = (Customer)JSON.deserialize(
            json, Customer.class
        );
        System.assertEquals('12345', customer.id);
    }
}

Common Issues and Solutions

1. Case Sensitivity

JSON is case-sensitive. Ensure your field names match exactly:

{
  "FirstName": "John",  // Different from firstName
  "lastName": "Doe"
}

2. Type Mismatches

Handle type conversions carefully:

public class Product {
    public String id;
    public Decimal price;  // Use Decimal for currency
    public Integer quantity;  // Use Integer for whole numbers
}

Integration Examples

Salesforce REST API

public static void callout() {
    Http http = new Http();
    HttpRequest request = new HttpRequest();
    request.setEndpoint('https://api.example.com/data');
    request.setMethod('GET');
    
    HttpResponse response = http.send(request);
    Customer customer = (Customer)JSON.deserialize(
        response.getBody(), 
        Customer.class
    );
}

Conclusion

Our JSON to Apex converter streamlines your integration development. Remember to:

  1. Validate your JSON input
  2. Test the generated classes
  3. Handle errors gracefully
  4. Follow Salesforce best practices

For more integration tips, check out our other guides!

Tags

JSONApexAPI IntegrationTools