0

I am working on a piece of code where we are creating a JSON string like below

JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartArray();
    gen.writeStartObject();
      gen.writeStringField('name', 'Account Name');
      gen.writeStringField('value', acc.Name);
    gen.writeEndObject();
gen.writeStartObject();
          gen.writeStringField('name', 'Account phone');
          gen.writeStringField('value', acc.phone);
       gen.writeEndObject();
       gen.writeStartObject();
          gen.writeStringField('name', 'xyz');
          gen.writeStringField('value', acc.xyz__c);
       gen.writeEndObject();
 gen.writeEndArray();
gen.writeEndObject();
gen.close(); 

Let's say xyz__c is null and I got the json exception, how can I throw an exception saying that which field is null. In Exception, I got line number, stack trace string, etc. but nothing to identify the parameter.

P.S. I don't want to put a null check on each and every key of the json.

0

I can't say I advocate that JSON, as you're generating a lot of unnecessary overhead; if you're allowed to change the format, I'd go with this:

return JSON.serialize(
    new Map<String, Object> {
        'accountName' => acc.Name,
        'accountPhone' => acc.Phone,
        'xyz' => acc.xyz__c
    });

But if you're using a generator, you'd have to check for null values. As it happens, though, you can simplify your code by using a field map:

Map<String, SObjectField> fieldMap = new Map<String, SObjectField> {
    'Account Name' => Account.Name,
    'Account Phone' => Account.Phone,
    'XYZ' => Account.XYZ__c
};
JSONGenerator gen = JSON.createGenerator(true);
gen.writeStartArray();
for(String fieldLabel: fieldMap.keySet()) {
    String fieldValue = (String)acc.get(fieldMap.get(fieldLabel));
    gen.writeStartObject();
    gen.writeStringField('name', fieldLabel);
    if(fieldValue == null) {
        gen.writeNullField('value');
    } else {
        gen.writeStringField('value', fieldValue);
    }
    gen.writeEndObject();
}
gen.writeEndArray();
gen.close();

Contrariwise, if you still wanted to throw an exception, you could modify the logic from above:

    if(fieldValue == null) {
        throw new JSONException(fieldLabel+' had a null value.');
    } else {

This would give you total control over the output of the exception by throwing it yourself.

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.