[SalesForce] Lightning JSON Formation Issue

I am getting the below error when I am passing json stringified string to server side method from client side controller in lightning.

Malformed JSON: Expected '{' at the beginning of object

Client side controller code

performAction1 : function(component){
    var action = component.get("c.performAction");
    var lstContactWrapper = component.get("v.contactWrapperList");
    var contactWrapperJSON = JSON.stringify(lstContactWrapper);
    console.log('wrapper json'+contactWrapperJSON);
    action.setParams({
        contactWrapper : contactWrapperJSON
    });

    action.setCallback(this,function(response){
        var state = response.getState();
        if(component.isValid() && state === 'SUCCESS'){
            alert('Success in calling server side action');
        }
        else if(state === 'ERROR'){
            alert('Error in calling server side action');  
        }
    });
    $A.enqueueAction(action);
}

server side code

public static void performAction(String contactWrapper){
    system.debug('contactWrapper:' +contactWrapper);

        List<Contact> selectedContacts = new List<Contact>();
        if(!String.isBlank(contactWrapper)){
            ****List<ContactWrapperLtng.DisplayContactRecords> lstContactWrapper = (List<ContactWrapperLtng.DisplayContactRecords>)JSON.deserialize(contactWrapper, ContactWrapperLtng.DisplayContactRecords.class);****
}

While deserailizing I am getting the above error.Please let me know how to resolve it.

Error Line

List lstContactWrapper = (List)JSON.deserialize(contactWrapper, ContactWrapperLtng.DisplayContactRecords.class);

Best Answer

You're deserializing into the wrong class. It should be:

JSON.deserialize(contactWrapper, List<ContactWrapperLtng.DisplayContactRecords>.class)

Right now you have:

JSON.deserialize(contactWrapper, ContactWrapperLtng.DisplayContactRecords.class)

Since you're trying to deserialize into a single Object instance, properly formed JSON would start with {. You're passing in a List, which starts with [.

Related Topic