1

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.

2

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);
| improve this answer | |
  • thanks @sfdcfox that explains why the constructors are not called, appreciate the detailed response. I understand better now – Anil Shivaraj Sep 27 '16 at 17:35
1

Your constructor is not called during the JSON parsing (See @sfdcfox's answer for more details). You didn't modify the auto-generated code to set a value as it parses the JSON, and frankly, you probably shouldn't modify the records there.

Once your code returns, you'll have access to all of the records, in the proper type, and you can iterate over them and set the Name field on each record to a const variable written somewhere in the calling code.

const String someName = 'Example';

// ... 

for (sObject s:n.Records) {
    if (String.isBlank(s.Name)) {
        s.Name = someName; 
    }
}

Much easier to maintain, and if you ever need to use your JSON parser for something else, you won't have to create a duplicate parser, or add a constructor parameter, or anything else- you'll just need to iterate over the records which are returned, and hey, you might need to modify a few other fields too- something you would have had to rewrite your JSON2Apex class to accomplish.

| improve this answer | |
1

Deserializing does not execute the parser method by itself.

You will need to execute the parser method similar to

String json = '{"records":"some value"}';
JSON2Apex(System.JSON.createParser(json));

However, in order to do what you want, set a static value for name you would simply:

public String Name { get { return 'My Name Value'; } set; }

Since the parser does not have a value to look for name anyway.

Note: if Name is not being set anywhere in the code, you can remove the setter.

| improve this answer | |
  • 1
    Having a set there seems kind of pointless, since it won't affect the get results. – Adrian Larson Sep 27 '16 at 16:39
  • @AdrianLarson - Yea, but since I do not think we have all the code, if the parser or anything else does try and set the "name" value, then we would get "it does not work" comments – Eric Sep 27 '16 at 16:40
  • 1
    Fair enough. Hmm...not a very good question perhaps. – Adrian Larson Sep 27 '16 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.