+ Start a Discussion
Parvinder ChanaParvinder Chana 

Json Serialization and Array

Hello, I'm working on integeration of SF with external application and need help wiht JSON and arrays

The following code is working fine and I'm getting what I need:

 Map<String,Object> msg = new Map<String,Object>();
        
 msg.put('channel', '#mychannel');
 msg.put('text', 'Here is my case number');
 msg.put('mrkdwn', true);
 String body = JSON.serialize(msg);

To extend above code, I need to achieve following JSON and not sure I can get this. Hope someone can help with this.
{
   "channel": "#mychannel"
    "text": "Here is my case number",  
    "attachments": [
        {
            "text": "And here is an attachment!",
            "color":"good",
            "footer":"End of Message"
        }
    ]
}


Thanks in advance,
P
Best Answer chosen by Parvinder Chana
Bryan JamesBryan James

Just a thought but you could make the inner json array as an inner class

//instantiate a new list to hold the attachments
List<Attachment> attachments = new List<Attachment>();

//loop through your list that you want to use for the attachments
for(sObject attachment : List<>){

instantiate a new attachment inner object and populate the values.
Attachment a = new Attachment();
a.text = attachment.text;
a.color = attachment.color;
a.footer = attachment.footer;
attachments.add(a);
}

msg.put('channel', '#mychannel');
msg.put('text', 'Here is my case number');
msg.put('mrkdwn', true);
//put the list into your msg Map
msg.put('attachments',attachments);

JSON.serialize(msg);

//Build an Attachment innerclass
public class Attachment {

String text;
String color;
String footer;

 

}

**More than likely Attachment is a reserved word so you might have to come up with something else.

All Answers

Bryan JamesBryan James

Just a thought but you could make the inner json array as an inner class

//instantiate a new list to hold the attachments
List<Attachment> attachments = new List<Attachment>();

//loop through your list that you want to use for the attachments
for(sObject attachment : List<>){

instantiate a new attachment inner object and populate the values.
Attachment a = new Attachment();
a.text = attachment.text;
a.color = attachment.color;
a.footer = attachment.footer;
attachments.add(a);
}

msg.put('channel', '#mychannel');
msg.put('text', 'Here is my case number');
msg.put('mrkdwn', true);
//put the list into your msg Map
msg.put('attachments',attachments);

JSON.serialize(msg);

//Build an Attachment innerclass
public class Attachment {

String text;
String color;
String footer;

 

}

**More than likely Attachment is a reserved word so you might have to come up with something else.

This was selected as the best answer
Parvinder ChanaParvinder Chana
Thanks Bryan. It solved my problem and worked like a charm. Appreciate the help!