1

I am trying to pass an array of objects from LWC to Apex but getting the error "Attempt to de-reference a null onbject". I googled and tried every possible way, but nothing seems to be working. What am I doing wrong. Below is my basic code snippet.

Map in LWC --

lwcmap = [{"key":"1","value":"test1"},{"key":"2","value":"test2"},{"key":"3","value":"test3"}]

method in LWC calling apex --

updateLVFilterData({MapofLWC : this.lwcmap}).then(data => {
 
 
}

Apex controller --

@AuraEnabled
    public static void mapofLWC( Map<Integer, String> MapofLWC){
        

        system.debug('MapofLWC - '+MapofLWC);
        
        }
        

3 Answers 3

3
  1. For Map<Integer,String> data type you are passing an Array of Objects of type containing String:String {"key":"1","value":"test1"} which is incorrect
  2. You need to set List<Map<string,String>> in your Aura Handler Apex Class, change it to this mapofLWC(List<Map<String, String>> MapofLWC) in your apex class
  3. The other workaround is that serialize your lwcMap object which would make it a string
  4. And in your aurHandler just make the input variable as String input
  5. And deserialize the input in your auraHandler Apex Class
1
  • @sfdc_spider do one thing serialize your ouput using JSON.serialize(lwcMap) and make your apex class accept (String MapofLWC) then in your apex class just deserialize it using JSON.deserialize or deserializeUnTyped or by using Inner Classes Commented Nov 9, 2022 at 14:17
2
public static void mapofLWC( Map<Integer, String> MapofLWC){

Should be:

public static void mapofLWC(List<Map<String, String>> MapofLWC){

Based on the demo JSON.

If you wanted to use the original Apex parameter data type, your JSON should look like:

lwcmap = {1: "test1", 2: "test2", 3: "test3"}
2

What you have in LWC is not a map, is a List (see it's an array, '[]'). So that what Apex should receive is a List<>.

Now the question is, list of what?

What you have in there is a Wrapper Object (inner class) that you can build, with the attribute 'Integer key', and the attribute 'String value'. If you want a map, it will be only valid a map of <String,String> in this case because a JSON is a Map with a String key, so you could pass something like this [{"1":"test1"},{"2":"test2"}] and in this case it could be a List<Map<String,String>>.

Hope it helps.

1
  • Hi All, I tried with List<Map<String, String>> as well. But still it is not able to recieve the data I passed from LWC. Value is showing as null in apex debug. Commented Nov 9, 2022 at 14:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .