Constructor not executed when deserializing JSON

apexjson

I have the following JSON data

{
    "objectName": "CustomObject__c",
    "fields": [
        {
            "name": "Field1__c",
            "extName": "ABC",
            "master": "System1"
        },
        {
            "name": "Field2__c",
            "extName": "DEF",
            "master": "System2"
        }
    ]
}

which I wanted to deserialize and added some more information in the target Apex object via its constructor:

public class JsonTest {

    public static void test() {
        String jsonData = '....';
        Schema s = (Schema)JSON.deserialize(jsonData, Schema.class);
        System.debug(s); // custom = null
    }

    public class Schema {
        String objectName;
        List<FieldItem> fields;
        String custom;
            
        public Schema() {
            custom = 'test';
        }
    }

    public class FieldItem {
        String name;
        String extName;
        String master;
    }
}

When I run my code JsonTest.test() via anonymous apex, the custom property is still null (although it has been set via the class constructor).
Why is it so?
Thanks.

Best Answer

It will remain null as you are attempting to deserialise JSON into the inner object that is either an empty object or an object without a value for the custom key.

If you call new Schema() (suggest a name change away from platform Schema) you will see custom=test. If you construct valid JSON to support the inner Schema object properties you will see the correct value also i.e String jsonData = '{"custom":"testing"}';

See JSON.deserialize won't call default constructor for more.

Related Topic