I need to create a JSON with information about Contacts of an Account, in order to send it to an webservice.
The thing is I can't find a way to create this JSON when a Account has more than a single Contact.
I'm currently testing with this apex method:
public static string createJSON(String ident){
String msj = '';
List<Contact> contactos = [select AccountId, RecordType.id, Phone, MobilePhone, BC_IE_celular2__c, BC_IE_Telefono_2__c, Extension_Usuario__c from Contact where accountId = :ident];
if(contactos.size() == 0){
msj = 'Account has 0 Contacts';
}else if(contactos.size() == 1){
msj = '[';
msj += '{';
msj += '"celular1": "'+contactos[0].MobilePhone+'", ';
msj += '"celular2": "'+contactos[0].BC_IE_celular2__c+'", ';
msj += '"telefono1": "'+contactos[0].Phone+'", ';
msj += '"telefono2": "'+contactos[0].BC_IE_Telefono_2__c+'", ';
msj += '"UserAnexo": "'+contactos[0].Extension_Usuario__c+'", ';
msj += '"ClientId": "'+contactos[0].AccountId+'", ';
msj += '"NroLista": "1" ';
msj += '}';
msj += ']';
}else if (contactos.size() > 1){
system.debug('this has '+contactos.size()+' contacts');
}
return msj;
}
I know this is not the best way to create a JSON, but is Working on Accounts with 0 or 1 Contact.
This is how must be the JSON with more than 1 Contacts in an Account
There is another way to serialize a JSON with Lists?
Thanks in advance.
JSON.serialize(contactos)
?