0

Im attempting to deserialize a JSON string into a custom apex class but Im getting a NULL value back from one particular node "transaction". Any ideas why its not translating from "transaction" to "transaction_Z"? (note: all the data included below is dummy data, not a real person)

String jsondata = '{"guid":"ABCXYZ123","payload":{"additionalPolicyHolders":[{"email":"lisa@example.com","firstName":"Lisa","lastName":"Hugo","primaryPhone":"(913) 555-7411"}],"animals":[{"ageIsUnderSeven":false,"ageIsUnderSevenDate":"2011-12-21T03:15:22.955688+00:00","altered":"Yes","animalId":"M7","birthdate":"2008-09-13T00:00:00","diagnoses":[{"examDate":"2018-12-20T06:00:00+00:00","medicalConditionDuration":"Chronic","medicalConditionId":"94a298d9-04cc-f4a8-2eef-28ef7abbfdee","medicalConditionResolutionDate":null,"notes":null,"veterinarianId":"613dfd1b-6c79-4f4c-5b58-33aa87f6b38b"}],"gender":"Male","microchipNumber":"MC99887","name":"Looper","primaryBreedId":"39d60923-8963-7b85-dc73-f53ae63d659c","primaryColorId":"50f29d68-44a1-c7ca-6b35-fdf45bf5e4d0","profilePhoto":null,"secondaryBreedId":"75a1d389-7cfe-842e-c939-d91d1b8f2ba1","secondaryColorId":"8c0b2481-3f69-2239-e899-ead97857cec6","species":"Cat","medicalFiles":[{"url":"https://petmedicalinternal.blob.core.windows.net/uploads/314a94d4-18f4-409c-a039-0a3e41f8dd51.txt","filename":"sample file 1.txt","sizeInBytes":13},{"url":"https://petmedicalinternal.blob.core.windows.net/uploads/fa21763b-bd31-476f-8d37-d086cbabf9a4.pdf","filename":"sample file 2.pdf","sizeInBytes":3028}]}],"billingAddress":{"addressLine1":"45 W 876th St","addressLine2":"Apt 2","city":"Las Vegas","state":"NV","zip":"88901"},"deviceId":"5200c61e46684575","email":"larry@example.com","firstName":"Larry","isAdvancePremiumPaymentAccepted":true,"isContactEmailAccepted":true,"isESignConsentAccepted":true,"isPreexistingConditionCoverageAccepted":true,"lastName":"Pippon","leadSource":"Agent App","organizationId":"94b70a81-c674-c83d-ad72-0b37331364af","policyTermId":"126a4914-86c7-44f3-f61e-fd830020d4ad","primaryAddress":{"addressLine1":"45 W 876th St","addressLine2":"Apt 2","city":"Las Vegas","state":"NV","zip":"88901"},"primaryPhone":"(913) 555-1343","secondaryPhone":"(913) 555-6236","signature":{},"transaction":"amount":"35.99","amountAuthorized":"35.99","authCode":"123456","avsResponse":"N","customerVaultId":"426809411","cvvResponse":"N","orderId":"abc","response":"1","responseCode":"100","responseText":"SUCCESS","transactionId":"bbb","type":"auth"}}}';


Class_LeadExport exportClass = (Class_LeadExport)JSON.deserialize(String.valueOf(jsondata), Class_LeadExport.class);
system.debug('exportClass--->'+exportClass.payload.transaction_Z);

Custom Apex Class

public class Class_LeadExport {

    public class BillingAddress {
        public String addressLine1 {get;set;} 
        public String addressLine2 {get;set;} 
        public String city {get;set;} 
        public String state {get;set;} 
        public String zip {get;set;} 

        public BillingAddress(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'addressLine1') {
                            addressLine1 = parser.getText();
                        } else if (text == 'addressLine2') {
                            addressLine2 = parser.getText();
                        } else if (text == 'city') {
                            city = parser.getText();
                        } else if (text == 'state') {
                            state = parser.getText();
                        } else if (text == 'zip') {
                            zip = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'BillingAddress consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class AdditionalPolicyHolders {
        public String email {get;set;} 
        public String firstName {get;set;} 
        public String lastName {get;set;} 
        public String primaryPhone {get;set;} 

        public AdditionalPolicyHolders(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'email') {
                            email = parser.getText();
                        } else if (text == 'firstName') {
                            firstName = parser.getText();
                        } else if (text == 'lastName') {
                            lastName = parser.getText();
                        } else if (text == 'primaryPhone') {
                            primaryPhone = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'AdditionalPolicyHolders consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Animals {
        public Boolean ageIsUnderSeven {get;set;} 
        public String ageIsUnderSevenDate {get;set;} 
        public String altered {get;set;} 
        public String animalId {get;set;} 
        public String birthdate {get;set;} 
        public List<Diagnoses> diagnoses {get;set;} 
        public String gender {get;set;} 
        public String microchipNumber {get;set;} 
        public String name {get;set;} 
        public String primaryBreedId {get;set;} 
        public String primaryColorId {get;set;} 
        public ProfilePhoto profilePhoto {get;set;} 
        public String secondaryBreedId {get;set;} 
        public String secondaryColorId {get;set;} 
        public String species {get;set;} 
        public List<MedicalFiles> medicalFiles {get;set;} 

        public Animals(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'ageIsUnderSeven') {
                            ageIsUnderSeven = parser.getBooleanValue();
                        } else if (text == 'ageIsUnderSevenDate') {
                            ageIsUnderSevenDate = parser.getText();
                        } else if (text == 'altered') {
                            altered = parser.getText();
                        } else if (text == 'animalId') {
                            animalId = parser.getText();
                        } else if (text == 'birthdate') {
                            birthdate = parser.getText();
                        } else if (text == 'diagnoses') {
                            diagnoses = arrayOfDiagnoses(parser);
                        } else if (text == 'gender') {
                            gender = parser.getText();
                        } else if (text == 'microchipNumber') {
                            microchipNumber = parser.getText();
                        } else if (text == 'name') {
                            name = parser.getText();
                        } else if (text == 'primaryBreedId') {
                            primaryBreedId = parser.getText();
                        } else if (text == 'primaryColorId') {
                            primaryColorId = parser.getText();
                        } else if (text == 'profilePhoto') {
                            profilePhoto = new ProfilePhoto(parser);
                        } else if (text == 'secondaryBreedId') {
                            secondaryBreedId = parser.getText();
                        } else if (text == 'secondaryColorId') {
                            secondaryColorId = parser.getText();
                        } else if (text == 'species') {
                            species = parser.getText();
                        } else if (text == 'medicalFiles') {
                            medicalFiles = arrayOfMedicalFiles(parser);
                        } else {
                            System.debug(LoggingLevel.WARN, 'Animals consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class MedicalFiles {
        public String url {get;set;} 
        public String filename {get;set;} 
        public Integer sizeInBytes {get;set;} 

        public MedicalFiles(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'url') {
                            url = parser.getText();
                        } else if (text == 'filename') {
                            filename = parser.getText();
                        } else if (text == 'sizeInBytes') {
                            sizeInBytes = parser.getIntegerValue();
                        } else {
                            System.debug(LoggingLevel.WARN, 'MedicalFiles consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Signature {
        public String bytes {get;set;} 
        public String contentType {get;set;} 
        public String filename {get;set;} 

        public Signature(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'bytes') {
                            bytes = parser.getText();
                        } else if (text == 'contentType') {
                            contentType = parser.getText();
                        } else if (text == 'filename') {
                            filename = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Signature consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class ProfilePhoto {
        public String bytes {get;set;} 
        public String contentType {get;set;} 
        public String filename {get;set;} 

        public ProfilePhoto(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'bytes') {
                            bytes = parser.getText();
                        } else if (text == 'contentType') {
                            contentType = parser.getText();
                        } else if (text == 'filename') {
                            filename = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'ProfilePhoto consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Payload {
        public List<AdditionalPolicyHolders> additionalPolicyHolders {get;set;} 
        public List<Animals> animals {get;set;} 
        public BillingAddress billingAddress {get;set;} 
        public String deviceId {get;set;} 
        public String email {get;set;} 
        public String firstName {get;set;} 
        public Boolean isAdvancePremiumPaymentAccepted {get;set;} 
        public Boolean isContactEmailAccepted {get;set;} 
        public Boolean isESignConsentAccepted {get;set;} 
        public Boolean isPreexistingConditionCoverageAccepted {get;set;} 
        public String lastName {get;set;} 
        public String leadSource {get;set;} 
        public String organizationId {get;set;} 
        public String policyTermId {get;set;} 
        public BillingAddress primaryAddress {get;set;} 
        public String primaryPhone {get;set;} 
        public String secondaryPhone {get;set;} 
        public Signature signature {get;set;} 
        public Transaction_Z transaction_Z {get;set;} // in json: transaction

        public Payload(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'additionalPolicyHolders') {
                            additionalPolicyHolders = arrayOfAdditionalPolicyHolders(parser);
                        } else if (text == 'animals') {
                            animals = arrayOfAnimals(parser);
                        } else if (text == 'billingAddress') {
                            billingAddress = new BillingAddress(parser);
                        } else if (text == 'deviceId') {
                            deviceId = parser.getText();
                        } else if (text == 'email') {
                            email = parser.getText();
                        } else if (text == 'firstName') {
                            firstName = parser.getText();
                        } else if (text == 'isAdvancePremiumPaymentAccepted') {
                            isAdvancePremiumPaymentAccepted = parser.getBooleanValue();
                        } else if (text == 'isContactEmailAccepted') {
                            isContactEmailAccepted = parser.getBooleanValue();
                        } else if (text == 'isESignConsentAccepted') {
                            isESignConsentAccepted = parser.getBooleanValue();
                        } else if (text == 'isPreexistingConditionCoverageAccepted') {
                            isPreexistingConditionCoverageAccepted = parser.getBooleanValue();
                        } else if (text == 'lastName') {
                            lastName = parser.getText();
                        } else if (text == 'leadSource') {
                            leadSource = parser.getText();
                        } else if (text == 'organizationId') {
                            organizationId = parser.getText();
                        } else if (text == 'policyTermId') {
                            policyTermId = parser.getText();
                        } else if (text == 'primaryAddress') {
                            primaryAddress = new BillingAddress(parser);
                        } else if (text == 'primaryPhone') {
                            primaryPhone = parser.getText();
                        } else if (text == 'secondaryPhone') {
                            secondaryPhone = parser.getText();
                        } else if (text == 'signature') {
                            signature = new Signature(parser);
                        } else if (text == 'transaction') {
                            transaction_Z = new Transaction_Z(parser);
                        } else {
                            System.debug(LoggingLevel.WARN, 'Payload consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public String guid {get;set;} 
    public Payload payload {get;set;} 

    public Class_LeadExport(JSONParser parser) {
        while (parser.nextToken() != System.JSONToken.END_OBJECT) {
            if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                String text = parser.getText();
                if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                    if (text == 'guid') {
                        guid = parser.getText();
                    } else if (text == 'payload') {
                        payload = new Payload(parser);
                    } else {
                        System.debug(LoggingLevel.WARN, 'Class_LeadExport consuming unrecognized property: '+text);
                        consumeObject(parser);
                    }
                }
            }
        }
    }

    public class Diagnoses {
        public String examDate {get;set;} 
        public String medicalConditionDuration {get;set;} 
        public String medicalConditionId {get;set;} 
        public String medicalConditionResolutionDate {get;set;} 
        public String notes {get;set;} 
        public String veterinarianId {get;set;} 

        public Diagnoses(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'examDate') {
                            examDate = parser.getText();
                        } else if (text == 'medicalConditionDuration') {
                            medicalConditionDuration = parser.getText();
                        } else if (text == 'medicalConditionId') {
                            medicalConditionId = parser.getText();
                        } else if (text == 'medicalConditionResolutionDate') {
                            medicalConditionResolutionDate = parser.getText();
                        } else if (text == 'notes') {
                            notes = parser.getText();
                        } else if (text == 'veterinarianId') {
                            veterinarianId = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Diagnoses consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }

    public class Transaction_Z {
        public String amount {get;set;} 
        public String amountAuthorized {get;set;} 
        public String authCode {get;set;} 
        public String avsResponse {get;set;} 
        public String customerVaultId {get;set;} 
        public String cvvResponse {get;set;} 
        public String orderId {get;set;} 
        public String response {get;set;} 
        public String responseCode {get;set;} 
        public String responseText {get;set;} 
        public String transactionId {get;set;} 
        public String type_Z {get;set;} // in json: type

        public Transaction_Z(JSONParser parser) {
            while (parser.nextToken() != System.JSONToken.END_OBJECT) {
                if (parser.getCurrentToken() == System.JSONToken.FIELD_NAME) {
                    String text = parser.getText();
                    if (parser.nextToken() != System.JSONToken.VALUE_NULL) {
                        if (text == 'amount') {
                            amount = parser.getText();
                        } else if (text == 'amountAuthorized') {
                            amountAuthorized = parser.getText();
                        } else if (text == 'authCode') {
                            authCode = parser.getText();
                        } else if (text == 'avsResponse') {
                            avsResponse = parser.getText();
                        } else if (text == 'customerVaultId') {
                            customerVaultId = parser.getText();
                        } else if (text == 'cvvResponse') {
                            cvvResponse = parser.getText();
                        } else if (text == 'orderId') {
                            orderId = parser.getText();
                        } else if (text == 'response') {
                            response = parser.getText();
                        } else if (text == 'responseCode') {
                            responseCode = parser.getText();
                        } else if (text == 'responseText') {
                            responseText = parser.getText();
                        } else if (text == 'transactionId') {
                            transactionId = parser.getText();
                        } else if (text == 'type') {
                            type_Z = parser.getText();
                        } else {
                            System.debug(LoggingLevel.WARN, 'Transaction_Z consuming unrecognized property: '+text);
                            consumeObject(parser);
                        }
                    }
                }
            }
        }
    }


    public static Class_LeadExport parse(String json) {
        System.JSONParser parser = System.JSON.createParser(json);
        return new Class_LeadExport(parser);
    }

    public static void consumeObject(System.JSONParser parser) {
        Integer depth = 0;
        do {
            System.JSONToken curr = parser.getCurrentToken();
            if (curr == System.JSONToken.START_OBJECT || 
                curr == System.JSONToken.START_ARRAY) {
                depth++;
            } else if (curr == System.JSONToken.END_OBJECT ||
                curr == System.JSONToken.END_ARRAY) {
                depth--;
            }
        } while (depth > 0 && parser.nextToken() != null);
    }


    private static List<Diagnoses> arrayOfDiagnoses(System.JSONParser p) {
        List<Diagnoses> res = new List<Diagnoses>();
        if (p.getCurrentToken() == null) p.nextToken();
        while (p.nextToken() != System.JSONToken.END_ARRAY) {
            res.add(new Diagnoses(p));
        }
        return res;
    }

    private static List<MedicalFiles> arrayOfMedicalFiles(System.JSONParser p) {
        List<MedicalFiles> res = new List<MedicalFiles>();
        if (p.getCurrentToken() == null) p.nextToken();
        while (p.nextToken() != System.JSONToken.END_ARRAY) {
            res.add(new MedicalFiles(p));
        }
        return res;
    }


    private static List<AdditionalPolicyHolders> arrayOfAdditionalPolicyHolders(System.JSONParser p) {
        List<AdditionalPolicyHolders> res = new List<AdditionalPolicyHolders>();
        if (p.getCurrentToken() == null) p.nextToken();
        while (p.nextToken() != System.JSONToken.END_ARRAY) {
            res.add(new AdditionalPolicyHolders(p));
        }
        return res;
    }

    private static List<Animals> arrayOfAnimals(System.JSONParser p) {
        List<Animals> res = new List<Animals>();
        if (p.getCurrentToken() == null) p.nextToken();
        while (p.nextToken() != System.JSONToken.END_ARRAY) {
            res.add(new Animals(p));
        }
        return res;
    }

}
  • 1
    You're supposed to use the parse method...not Class_LeadExport exportClass = (Class_LeadExport)JSON.deserialize(...). – Adrian Larson Jan 10 at 22:15
4

Looking at your code it seems like you have a ton of extra code all for the singular reason that your JSON has a reserved word as a member name.

Option 1:

The easy solution is to use untyped deserialization:

Map<String, Object> payload = JSON.deserializeUntyped(jsondata)

this should be good enough. You can access anything the same way you would in a map:

Map<String, Object> transaction = (Map<String, Object>) payload.get('transaction');
String amount = (String) transaction.get('amount');

Option 2

Pre-process the JSON to remove the reserved word from the JSON and then you can use deserialization to create your objects (credit: cropredy)

jsondata.replace('transaction', 'transaction_Z');
Class_LeadExport exportClass =
    (Class_LeadExport)JSON.deserialize(String.valueOf(jsondata), Class_LeadExport.class);

Option 3

That being said, if you insist on continuing to use your custom classes, what Adrian said in the comments is correct, it should be

JSONParser jsonparser = JSON.createParser(jsondata);
Class_LeadExport exportClass = new Class_LeadExport(jsonparser);
  • 2
    or .. if possible, preprocess JSON (using String method replace) and convert reserved word attributes from somereservedword to somereservedwordX and then the deserialization is trivial into apex types – cropredy Jan 11 at 4:08
  • Added it to the answer. – gNerb Jan 11 at 14:32
  • All - thank you for the help, you all have saved me alot of time. I tried the simple fix with Option 3 and that seems to be working. Although in the future I will start with Option 1, very simple solution. Again -thank you all for your help! – user891859 Jan 11 at 16:41

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.