Skip to content

JSON to SObjects

Nikiforov Alexey edited this page Jul 9, 2017 · 10 revisions

Example

Only plain JSON is supported.

@isTest static void test() {
    //Arrange
    SObjectMapper.initialize(
        new MapperConfigBuilder('LeadFromJson')
            .addObjectMapping('Account', '*')
            .addObjectMapping('Contact', new List<String>{'Email', 'City'})
            .addFieldMapping('City', 'MailingCity')
            .addFieldMapping('numbOfEmployees', 'NumberOfEmployees')
    );
    Map<String, String> leadJson = new Map<String, String>{
        'Email' => 'testlead@test.com',
        'City' => 'test address',
        'numbOfEmployees' => '3'
    };
    //Act
    Map<String, sObject> result = SObjectMapper.mapObject(
        new JsonResourceProvider(JSON.serialize(leadJson), 'LeadFromJson')
    );
    Contact contact = (Contact)result.get('Contact');
    Account account = (Account)result.get('Account');
    
    //Assert
    system.assertEquals(leadJson.get('City'), contact.MailingCity);
    system.assertEquals(leadJson.get('Email'), contact.Email);
    system.assertEquals(Integer.valueOf(leadJson.get('numbOfEmployees')), account.NumberOfEmployees);
}