[SalesForce] Return List from Apex controller to lightning component

All my code

Saved as DX project in my github repo

I have a lightning component contains:

  1. client Controller function doInit call Apex Controller getTreefunction and print out received data in console.log
  2. getTree function returns a list of TreeNode class with id and name attributes

My issue is:

I do not think @AuraEnabled is needed for id and name in TreeNode class. However, if I remove @AuraEnabled, they are gone in console.log.

For example, if I remove @AuraEnabled from name in TreeNode class,
console.log prints below, without name key:value pair anymore.

result: 
[
  {
    "id": "0016E00000UFOPTQA5"
  }
]

Key code file (all code are saved in my github repo

Client controller js

({
    doInit: function(component, event, helper) {
        var action = component.get("c.getTree");
        var cb = function(response) {
            console.log(
                "result: \n" + JSON.stringify(response.getReturnValue(), null, 2) + "\n"
            );
        };
        helper.apexCall(component, action, {}, cb);
    }
});

Apex Controller cls

public class testApexController {
    @AuraEnabled
    public static List<TreeNode> getTree()
    {
        List<Account> allAccounts = [SELECT Id, Name FROM Account];

        List<TreeNode> tree = new List<TreeNode>();

        addAccounts(tree, allAccounts);
        System.debug('test tree nodes: ' + tree);
        return tree;
    }

    private static void addAccounts(List<TreeNode> tree, List<Account> accounts){
        for (Account a : accounts){
            TreeNode node = new TreeNode(a.id, a.name);
            tree.add(node);
        }
    }
}

TreeNode class

public class TreeNode {
    @AuraEnabled
    public String id;

    @AuraEnabled
    public String name;

    public TreeNode(String id, String name){
        this.id = id;
        this.name = name;
    }
}

All my code

Saved as DX project in my github repo

Best Answer

Yes, @AuraEnabled is required for attributes to be serialized. This is mentioned in the documentation:

  • Use @AuraEnabled on Apex class static methods to make them accessible as remote controller actions in your Lightning components.

  • Use @AuraEnabled on Apex instance methods and properties to make them serializable when an instance of the class is returned as data from a server-side action.