Here are code samples that demonstrate DataWeave in Apex.
To use DataWeave in Apex, follow these instructions with associated examples.
- Create a DataWeave script source file. For example: csvToContacts.dwl.
%dw 2.0 input records application/csv output application/apex --- records map(record) -> { FirstName: record.first_name, LastName: record.last_name, Email: record.email } as Object {class: "Contact"} - Create the associated metadata file.
For example: csvToContacts.dwl-meta.xml.
<?xml version="1.0" encoding="UTF-8"?> <DataWeaveResource xmlns="http://soap.sforce.com/2006/04/metadata"> <apiVersion>58.0</apiVersion> <isGlobal>false</isGlobal> </DataWeaveResource>
- Push the source to the scratch org using Salesforce CLI version v7.151.9 or higher. See Salesforce CLI Release Notes.
- Invoke the DataWeave script from Apex and check the results from anonymous
Apex.This example invokes the csvToContacts.dwl script.
// CSV data for Contacts String inputCsv = 'first_name,last_name,email\nCodey,"The Bear",codey@salesforce.com'; DataWeave.Script dwscript = new DataWeaveScriptResource.csvToContacts(); DataWeave.Result dwresult = dwscript.execute(new Map<String, Object>{'records' => inputCsv}); List<Contact> results = (List<Contact>)dwresult.getValue(); Assert.areEqual(1, results.size()); Contact codeyContact = results[0]; Assert.areEqual('Codey',codeyContact.FirstName); Assert.areEqual('The Bear',codeyContact.LastName);