There are group of fields I am querying and putting them in JSON. Some of these fields may be blank which is making previous test classes fail throwing a nul pointer exception.
**Present Code ** There are many other fields. I am just putting a sample
gen.writeStringField('DayPhone', c.contact.OtherPhone);
gen.writeStringField('EveningPhone', c.contact.HomePhone);
gen.writeStringField('WorkPhone', c.contact.phone), c.account.Billing_Account_Number__c);
Currently, I have to write if condition like this for it to work:
if(c.contact.HomePhone != null){gen.writeStringField('EveningPhone', c.contact.HomePhone);}
if(c.contact.phone != null){gen.writeStringField('WorkPhone', c.contact.phone);}
if(c.contact.MobilePhone != null){gen.writeStringField('Mobile', c.contact.MobilePhone);}
Since I am adding if on every line, I wanted to know if any check can be done all at once or any other option.
**Update ** I found that using JSON serialize can avoid this exception. So I am planning to change my code from JSON Generator to serialize instead of writing if condition on all fields. But is there a way to add if condition while serializing.
Ex: When I use JSONGenerator I can add if condition like this:
if(c.accountId != null){ gen.writestringfield(c.accountId); }
which adds this value to json only if accountid is not null. But in case of serialize, it is
public class caseVars {
public string caseId;
public string accountId;
}
public static void postCases (list<case> c1) {
for(case c: c1){
caseVars caseVar = new caseVars();
caseVar.caseId = IdSplit(c.Id);
if(c.accountId != null){ caseVar.accountId = c.accountId; }
}
I believe in the second method, evenif accountId is null, there is a label named accountId with null value in the Jsonstring. Is there a way to control that ? ( Is there a way not to show accountId field at all in JSON string if there is no accountId on case)
Thanks