You need to sign in to do that
Don't have an account?

JSON Body in Apex
Hi All,
I would like to prepare dynamic JSON body for all the contact records with masked values like below mentioned format. If contact field value is exist in need to send it as True, if it is not exist send it as False. How to achieve this apex.
{
"Id":"0032800000240hnAAA",
"Name": "True",
"LastName": "True",
"OtherAddress":"Flase",
"MailingAddress":"True",
"Phone":"True",
},
{
"Id":"0032800000240hnAAA",
"Name": "False",
"LastName": "True",
"OtherAddress":"True",
"MailingAddress":"True",
"Phone":"True",
}
Thanks,
Anil Kumar
I would like to prepare dynamic JSON body for all the contact records with masked values like below mentioned format. If contact field value is exist in need to send it as True, if it is not exist send it as False. How to achieve this apex.
{
"Id":"0032800000240hnAAA",
"Name": "True",
"LastName": "True",
"OtherAddress":"Flase",
"MailingAddress":"True",
"Phone":"True",
},
{
"Id":"0032800000240hnAAA",
"Name": "False",
"LastName": "True",
"OtherAddress":"True",
"MailingAddress":"True",
"Phone":"True",
}
Thanks,
Anil Kumar
Here is the sample code, Please modify as per your JSON object.
There are two ways you can form JSON. One is using JSON Generator Method and other would be using JSON Serializer (for this we creat a Wrapper Class). Above code is perfeclty fine with just one simple change like if you want to use boolean values then its better if we use writeBooleanField (Refere to JSONGenerator Class (https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_class_System_JsonGenerator.htm)).
List<Contact> lstCnts = [Select Id, Name, LastName, OtherAddress, MailingAddress, Phone From Contact];
Lets say if above is your Contact List, then you can form JSON as below using JSONGenerator
String jsonBody;
if (lstCnts.size()>0) {
JSONGenerator jsonGen = JSON.createGenerator(true);
for (Contact c: lstCnts) {
jsonGen.writeStartObject();
jsonGen.writeStringField('Id', c.Id);
jsonGen.writeStringField('Name', c.Name);
jsonGen.writeStringField('LastName', c.LastName);
jsonGen.writeStringField('MailingAddress', String.ValueOf(c.OtherAddress));
jsonGen.writeStringField('MailingAddress', String.ValueOf(c.MailingAddress));
if (c.Phone != null) {
jsonGen.writeBooleanField('Phone', True);
} else {
jsonGen.writeBooleanField('Phone', False);
}
jsonGen.writeEndObject();
jsonBody = jsonGen.getAsString();
jsonGen.close();
System.debug('************JSON BODY************' + jsonBody);
}
}
Also make sure your fields (OtherAddress, MailingAddress) return some values other wise you will end up hitting "System.NullPointerException: null argument for JSONGenerator.writeStringField()"!