[SalesForce] Default values for Wrapper variables not set

i am stumbled upon a issue and questioning why i didn't do a strong learning in oops. Below is a small snippet which is giving me the issue, i have a wrapper class built by json2apex tool. It is a simple wrapper which has a name as a string variable and i would like to hardcode the name to be always a static string.

public class Records {
    public String Name {get;set;} 

        public Records(JSONParser parser) {
            Name = 'hello';
        }
}

public JSON2Apex(JSONParser parser) {
        while (parser.nextToken() != JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != JSONToken.VALUE_NULL) {
                    if (text == 'totalSize') {
                        totalSize = parser.getIntegerValue();
                    } else if (text == 'done') {
                        done = parser.getBooleanValue();
                    } else if (text == 'nextRecordsUrl') {
                        nextRecordsUrl = parser.getText();
                    } else if (text == 'records') {
                        records = new List<Records>();
                        while (parser.nextToken() != JSONToken.END_ARRAY) {
                            records.add(new Records(parser));
                        }
                    } else {
                        System.debug(LoggingLevel.WARN, 'Root consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }

Below is my snippet to make the JSON.deserialize to make sure things my string is parsed into objects as defined in the wrapper.

JSON2Apex n = (JSON2Apex)JSON.deserialize('{Some String value}', JSON2Apex.class);

System.debug('Record Detai'+n.Records);

When this class get invoked i would assume that all the records variable will have the 'Name' value set to 'hello' but the value doesn't get set and stays as null.

01:37:19:367 USER_DEBUG [39]|DEBUG|Record Detai(Records:[Name=null])

Is there any reason for value not being set, my goal is to default the Name variable to a value incase its null.

Best Answer

Constructors are ignored when using JSON.deserialize. Consider this trivial Execute Anonymous code:

class Example {
    String privateMember { get; set { privateMember = value.repeat(3); } }
    Example() {
        System.assert(false);
    }
}

Example value = (Example)JSON.deserialize('{"privateMember":"abc"}', Example.class);

System.debug(value.privateMember);

If the constructor were called, the execution would halt.

Similarly, your JSON2Apex constructor isn't called. Instead, you need to construct a JSONParser with your JSON data, then create a new JSON2Apex parser:

JSONParser p = JSON.createParser(myString);
JSON2Apex j2a = new JSON2Apex(p);
Related Topic