Essential JSON Handling in Salesforce (Apex + LWC)

Essential JSON Handling in Salesforce (Apex + LWC)

Essential JSON Handling in Salesforce (Apex + LWC)

1. JSON Handling in Apex

A. Convert Apex Objects to JSON (JSON.serialize())

Serialization means converting an Apex object to a JSON string.

public class Student {
    public String name;
    public Integer age;

    public Student(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

// Convert Apex object to JSON string
Student s = new Student('John', 23);
String jsonString = JSON.serialize(s);
System.debug('JSON Output: ' + jsonString);
Output: {"name":"John","age":23}

B. Convert JSON to Apex Objects (JSON.deserialize())

String jsonInput = '{"name":"John","age":23}';
Student parsedStudent = (Student) JSON.deserialize(jsonInput, Student.class);
System.debug('Student Name: ' + parsedStudent.name);
Output: Student Name: John

C. Convert JSON to Generic Apex Data Structure (JSON.deserializeUntyped())

String jsonInput = '{"name":"John","age":23}';
Map<String, Object> studentMap = (Map<String, Object>) JSON.deserializeUntyped(jsonInput);
System.debug('Student Name: ' + studentMap.get('name'));
Output: Student Name: John

D. Handling Lists (Arrays) in JSON

String jsonArray = '[{"name":"John","age":23}, {"name":"Alice","age":25}]';
List<Student> students = (List<Student>) JSON.deserialize(jsonArray, List<Student>.class);
System.debug('First Student Name: ' + students[0].name);
Output: First Student Name: John

E. Nested JSON Handling in Apex

public class Course {
    public String title;
    public Student student;

    public class Student {
        public String name;
        public Integer age;
    }
}

String nestedJson = '{"title":"Math","student":{"name":"John","age":23}}';
Course courseObj = (Course) JSON.deserialize(nestedJson, Course.class);
System.debug('Student Name: ' + courseObj.student.name);
Output: Student Name: John

2. JSON Handling in LWC (JavaScript)

A. Convert JavaScript Object to JSON (JSON.stringify())

const student = {
    name: "John",
    age: 23
};
const jsonString = JSON.stringify(student);
console.log(jsonString);
Output: {"name":"John","age":23}

B. Convert JSON to JavaScript Object (JSON.parse())

const jsonString = '{"name":"John","age":23}';
const studentObj = JSON.parse(jsonString);
console.log(studentObj.name);
Output: John

C. Sending JSON Data from LWC to Apex

import { LightningElement, track } from 'lwc';
import saveStudent from '@salesforce/apex/StudentController.saveStudent';

export default class StudentComponent extends LightningElement {
    @track student = { name: "John", age: 23 };

    sendToApex() {
        let studentJSON = JSON.stringify(this.student);
        saveStudent({ studentData: studentJSON })
            .then(result => console.log(result))
            .catch(error => console.error(error));
    }
}

D. Receiving JSON Data in Apex

public with sharing class StudentController {
    @AuraEnabled
    public static String saveStudent(String studentData) {
        Map<String, Object> studentMap = (Map<String, Object>) JSON.deserializeUntyped(studentData);
        System.debug('Received Student: ' + studentMap);
        return 'Student Saved!';
    }
}

E. Fetching Data from Apex to LWC

import { LightningElement, track, wire } from 'lwc';
import getStudents from '@salesforce/apex/StudentController.getStudents';

export default class StudentList extends LightningElement {
    @track students;

    @wire(getStudents)
    wiredStudents({ error, data }) {
        if (data) {
            this.students = JSON.parse(data);
        } else if (error) {
            console.error(error);
        }
    }
}
public with sharing class StudentController {
    @AuraEnabled(cacheable=true)
    public static String getStudents() {
        List<Student__c> students = [SELECT Name, Age__c FROM Student__c];
        return JSON.serialize(students);
    }
}

3. JSON Handling in API Integrations

A. Outbound Callout (Salesforce → External API)

public class CalloutExample {
    public static void sendStudentData() {
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://api.example.com/students');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json');

        // Convert Apex object to JSON
        Student student = new Student('John', 23);
        req.setBody(JSON.serialize(student));

        Http http = new Http();
        HttpResponse res = http.send(req);
        System.debug('Response: ' + res.getBody());
    }
}

B. Inbound API (External System → Salesforce)

@RestResource(urlMapping='/students')
global with sharing class StudentAPI {
    @HttpPost
    global static String createStudent(String studentData) {
        Student student = (Student) JSON.deserialize(studentData, Student.class);
        insert student;
        return 'Student Created!';
    }
}

Key Takeaways

Scenario Apex Method LWC Method
Convert Object to JSON JSON.serialize(obj) JSON.stringify(obj)
Convert JSON to Object JSON.deserialize(json, ClassName.class) JSON.parse(json)
Convert JSON to Map JSON.deserializeUntyped(json) JSON.parse(json)
Send Data to Apex Receive as String & Deserialize JSON.stringify(obj) before sending
Get Data from Apex JSON.serialize(result) before returning JSON.parse(data) after receiving

Would you like me to create a full working LWC + Apex integration with JSON? 🚀

Comments

Popular posts from this blog

Understanding Note and ContentNote Objects in Salesforce

OOPS in Apex

System administrator gets logged out when they use 'Login as User'