0

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  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.

5
  • 1
    Have you tried JSON.serialize(contactos)?
    – gNerb
    Commented Jan 8, 2020 at 19:17
  • yes, but the result shows "attributes": { "type": "Contact", "url": "/services/data/v48.0/sobjects/Contact/003e000001GIqu1AAD" }, and "RecordType": { "attributes": { "type": "RecordType", "url": "/services/data/v48.0/sobjects/RecordType/012c0000000Dp61AAC" }, "Id": "012c0000000Dp61AAC" }. There is any way to skip those things? Commented Jan 8, 2020 at 19:28
  • 1
    Why do you want to skip them? Is it causing errors for you?
    – gNerb
    Commented Jan 8, 2020 at 19:38
  • Not causing troubles for me, but my client needs only what is in the image example. Commented Jan 8, 2020 at 19:42
  • 1
    You should push back and see if they can just ignore "extra" properties in the JSON. It should be trivial for most implementations.
    – Adrian Larson
    Commented Jan 8, 2020 at 19:44

2 Answers 2

1

If you REALLY need to remove the extra parts of the JSON try the following:

List<Contact> contacts = [SELECT Id FROM Contact LIMIT 5];
String j = JSON.serialize(contacts);
List<Object> untyped = (List<Object>) JSON.deserializeUntyped(j);

for (Object o : untyped) {
    Map<String, Object> contact = (Map<String, Object>) o;

    contact.remove('attributes');
    contact.remove('RecordType');
}

system.debug(json.serialize(untyped));

Here is an answer I wrote a while back on dealing with dynamic json.

I would strongly advise just serializing the list and sending it out. The receiving server should be smart enough to only parse the bits they care about and ignore the rest.

1
  • Probably vastly more efficient to just use getPopulatedFieldsAsMap.
    – Adrian Larson
    Commented Jan 8, 2020 at 20:22
0

I've found a good solution in this code:

List<Map<String, Object>> mm = new List<Map<String, Object>>();
for (Lead l : [
        SELECT Email, First_Name__c, Last_Name__c ,lead_ag__C, Agency_Type__c
        FROM Lead
        WHERE Id in :leads
        ]) {
    Map<String, Object> m = new Map<String, Object>{
        'email' => l.Email,
        'first_name' => l.First_Name__c,
        ...
    };
    mm.add(m);
}

It worked like a charm, but instead of inserting the data as in the order of the image example, I had to inver the order, so it worked as:

List<Map<String,Object>> mm = new List<Map<String,Object>>();
for(Contact con : contactos){
    Map<String, Object> m = new Map<String, Object>{
        'NroLista' => '1',
        'ClientId' => con.AccountId,
        'UserAnexo' => con.Extension_Usuario__c,
        'telefono2' => con.BC_IE_Telefono_2__c,
        'telefono1' => con.Phone,
        'celular2' => con.BC_IE_celular2__c,
        'celular1' => con.MobilePhone
    };
    mm.add(m);
}

String jsonString = JSON.serialize(mm);

The result looks like:

[
    {
        "NroLista": 1,
        "ClientId": "001e000001Tf6xuAAB",
        "UserAnexo": "4321",
        "telefono2": "987811666",
        "telefono1": "987811666",
        "celular2": "+51987811666",
        "celular1": "+51987811666"
    },
    {
        "NroLista": 1,
        "ClientId": "001e000001Tf6xuAAB",
        "UserAnexo": "4321",
        "telefono2": "987811666",
        "telefono1": "987811666",
        "celular2": "+51987811666",
        "celular1": "+51987811666"
    },
    {
        "NroLista": 1,
        "ClientId": "001e000001Tf6xuAAB",
        "UserAnexo": "4321",
        "telefono2": "987811666",
        "telefono1": "987811666",
        "celular2": "+51987811666",
        "celular1": "+51987811666"
    }
]

Using an Account with 3 Contacts.

The original solution is here:

JSON structure?

Thanks all.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .