Working with Salesforce Data · Lesson 10 of 25
JSON Between Apex and LWC
Every call between a component and Apex travels as JSON. Most of the time the platform converts it for you, so it's easy to forget it's there – until a date arrives as a string, a field is mysteriously missing, or someone returns a JSON string from Apex and you end up parsing twice. This lesson shows what actually happens on the wire.
In this lesson
- How Apex return values reach JavaScript
- Wrapper classes vs returning JSON strings
- Sending objects to Apex
- JSON.parse and JSON.stringify in practice
What Apex sends, what JavaScript gets
The round trip
- Apex method returnssObjects, lists, maps or a wrapper class
- Platform serialisesto JSON; null fields are left out of sObjects
- LWC receivesplain JavaScript objects and arrays – already parsed
- Your codereads properties; dates and datetimes are ISO strings
public with sharing class AccountSummaryController {
public class AccountSummary {
@AuraEnabled public String name;
@AuraEnabled public Decimal revenue;
@AuraEnabled public Date lastActivity;
@AuraEnabled public List<String> openCases;
}
@AuraEnabled(cacheable=true)
public static AccountSummary getSummary(Id accountId) {
Account a = [SELECT Name, AnnualRevenue, LastActivityDate FROM Account WHERE Id = :accountId WITH USER_MODE];
AccountSummary s = new AccountSummary();
s.name = a.Name;
s.revenue = a.AnnualRevenue;
s.lastActivity = a.LastActivityDate;
s.openCases = new List<String>();
for (Case c : [SELECT Subject FROM Case WHERE AccountId = :accountId AND IsClosed = false WITH USER_MODE]) {
s.openCases.add(c.Subject);
}
return s;
}
}
Only properties marked @AuraEnabled are sent. In JavaScript the result is a ready-to-use object – no JSON.parse needed:
// what the component receives from getSummary (already an object)
const summary = { name: 'Acme', revenue: 2500000, lastActivity: '2026-10-28', openCases: ['Login issue', 'Invoice copy'] };
console.log(typeof summary, summary.openCases.length);
console.log(typeof summary.lastActivity); // Date → 'YYYY-MM-DD' string
const last = new Date(`${summary.lastActivity}T00:00:00`); // parse as local midnight
console.log(last.toDateString());
object 2 string Wed Oct 28 2026
- Apex
Datearrives as"2026-10-28";Datetimeas an ISO string in UTC, e.g."2026-10-28T09:30:00.000Z". - A
Map<String, Object>arrives as a plain object; aMap<Id, Account>as an object keyed by Id. - Blank sObject fields are missing; null wrapper properties arrive as missing too – code defensively with
??.
Don't return JSON strings from Apex
You'll see older code like return JSON.serialize(results); with a String return type. The component then has to JSON.parse it, you lose type information, and – if someone forgets – the template shows the raw string. Return the object or wrapper class instead and let the platform do the work. The exception is a genuinely dynamic structure you store as JSON text, such as a configuration field.
// a JSON string stored in a custom field or custom metadata
const configText = '{"pageSize":20,"showClosed":false,"columns":["Name","Stage"]}';
function readConfig(text) {
try {
return { pageSize: 10, showClosed: true, columns: ['Name'], ...JSON.parse(text) };
} catch (e) {
console.warn(`Bad config, using defaults: ${e.message}`);
return { pageSize: 10, showClosed: true, columns: ['Name'] };
}
}
console.log(readConfig(configText));
console.log(readConfig('{pageSize: 20}')); // keys must be in double quotes
{ pageSize: 20, showClosed: false, columns: [ 'Name', 'Stage' ] }
Bad config, using defaults: Expected property name or '}' in JSON at position 1 (line 1 column 2)
{ pageSize: 10, showClosed: true, columns: [ 'Name' ] }
Always wrap JSON.parse of stored or user-provided text in try/catch and fall back to defaults – a single typo in a config record shouldn't break the page.
Sending objects to Apex
Parameters of an imperative call are passed as one object whose keys match the Apex parameter names. Objects and lists are converted to the Apex types automatically:
public with sharing class LeadController {
public class LeadInput {
@AuraEnabled public String lastName { get; set; }
@AuraEnabled public String company { get; set; }
@AuraEnabled public List<String> interests { get; set; }
}
@AuraEnabled
public static Id createLead(LeadInput input) {
Lead l = new Lead(LastName = input.lastName, Company = input.company,
Description = String.join(input.interests, ', '));
insert as user l;
return l.Id;
}
}
import createLead from '@salesforce/apex/LeadController.createLead';
// inside the component
async handleSave() {
const input = { lastName: this.lastName, company: this.company, interests: [...this.interests] };
this.leadId = await createLead({ input }); // key "input" = the Apex parameter name
}
Wrapper classes used as parameters need { get; set; }
Apex can only fill properties of an input wrapper that have accessors and @AuraEnabled. Without them the values silently arrive as null. Also pass plain copies ([...this.interests]) rather than proxies of read-only data.
JSON.stringify for debugging and storage
const record = { Id: '001A', Name: 'Acme', Owner: { Name: 'Asha' }, secretToken: 'abc123', CreatedDate: new Date(Date.UTC(2026, 10, 1)) };
console.log(JSON.stringify(record));
console.log(JSON.stringify(record, ['Id', 'Name'])); // only these keys
console.log(JSON.stringify(record, (key, value) => (key === 'secretToken' ? undefined : value), 2));
{"Id":"001A","Name":"Acme","Owner":{"Name":"Asha"},"secretToken":"abc123","CreatedDate":"2026-11-01T00:00:00.000Z"}
{"Id":"001A","Name":"Acme"}
{
"Id": "001A",
"Name": "Acme",
"Owner": {
"Name": "Asha"
},
"CreatedDate": "2026-11-01T00:00:00.000Z"
}
JSON.stringify(value, null, 2) is the quickest way to see what's inside an LWC proxy in the console, and a replacer function lets you hide sensitive fields before logging or storing anything.
Practice
Try it yourself
The template shows
[{"Id":"001A","Name":"Acme"}]as text instead of a list. What's likely wrong in Apex, and what's the better fix?Show answer
The method returns
JSON.serialize(accounts)as a String. Change the return type toList<Account>and return the list; the component receives an array directly.Apex receives
nullfor every field of your wrapper parameter. What should you check?Show answer
That each wrapper property is
@AuraEnabledwith{ get; set; }, and that the JavaScript object keys exactly match the Apex property names (case matters) and the call uses the parameter name as the key.
Quick check
Do you need JSON.parse for a List<Account> returned from Apex?
No – it arrives as a JavaScript array.
How does an Apex Date arrive?
As a "YYYY-MM-DD" string.
What does the second argument of JSON.stringify do?
Filters or transforms values – an array of keys or a replacer function.
Summary
- Apex results arrive already parsed; only @AuraEnabled properties are sent.
- Dates are strings – convert deliberately; blank fields are missing.
- Return objects or wrappers, not JSON strings; parse stored JSON inside try/catch.
- Input wrappers need @AuraEnabled with get/set; keys must match Apex names.
Finished this lesson?
Mark it complete to track your progress, then carry on with the next lesson.