Writing Apex

General

Using today date

Date todayDate = Helper.today;
List<Contact> contacts = [SELECT Name, Title, Linkedin__c, Email FROM Contact WHERE Expected_Follow_Up_Date__c < :todayDate];
Date lastWeekDate = Helper.today.addDays(-7);

Note: need to use Helper.today since Helper.today can be edited during testing.

Add List to List

List<Contact> contacts1 = New List<Contact>();
List<Contact> contacts2 = New List<Contact>();
contacts1.addAll(contacts2);

Pass List as parameter

List<Opportunity> opportunities = ApplicationController.create(new List<ApplicationController.OpportunityDetail>{
    new ApplicationController.OpportunityDetail(opportunities[0].Id),
    new ApplicationController.OpportunityDetail(opportunities[1].Id)
});
'/lightning/r/Contact/{!Result.Id}/view'
'/lightning/r/Opportunity/' + item['Id'] + '/view'

List of Contact

// JSON string representing a list of contacts
String contactsJson = '[' +
    '{"FirstName": "John", "LastName": "Doe", "Email": "john@example.com"},' +
    '{"FirstName": "Jane", "LastName": "Smith", "Email": "jane@example.com"}' +
']';

// Deserialize the JSON string into a List<Contact>
List<Contact> contacts = (List<Contact>) JSON.deserialize(contactsJson, List<Contact>.class);

// Print the deserialized contacts
for (Contact contact : contacts) {
    System.debug('Contact: ' + contact.FirstName + ' ' + contact.LastName + ', Email: ' + contact.Email);
}

// Output
// Contact: John Doe, Email: john@example.com
// Contact: Jane Smith, Email: jane@example.com

List of String

// JSON string representing a list of strings
String stringsJson = '["Apple", "Banana", "Orange"]';

// Deserialize the JSON string into a List<String>
List<String> fruits = (List<String>) JSON.deserialize(stringsJson, List<String>.class);

// Print the deserialized strings
for (String fruit : fruits) {
    System.debug('Fruit: ' + fruit);
}

// Output
// Fruit: Apple
// Fruit: Banana
// Fruit: Orange

From JSON string

public class Person {
    public String name;
    public Integer age;
    public String email;
}

// JSON string representing a person
String jsonString = '{"name":"John Doe","age":30,"email":"john@example.com"}';

// Deserialize the JSON string into a Person object
Person person = (Person) JSON.deserialize(jsonString, Person.class);

// Access the deserialized properties
System.debug(person.name);  // Output: John Doe
System.debug(person.age);   // Output: 30
System.debug(person.email); // Output: john@example.com

To generate an Apex class from a JSON object automatically, you can use JSON2Apex.

Author

Edward Wong

Last updated