I need to implement a Java method to return a JSON. Here is the desired JSON output that I need to produce.
{
"channel": "channelId",
"thread_ts": "threadId",
"reply_broadcast": true,
"attachments": [{
"color": "#2F8AB7",
"blocks": [{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Test header text"
}
},
{
"type": "divider"
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Test text 01"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Here",
"emoji": true
},
"url": "https://mycompany.com/link1"
}
},
{
"type": "section",
"text": {
"type": "mrkdwn",
"text": "Test text 02"
},
"accessory": {
"type": "button",
"text": {
"type": "plain_text",
"text": "Click Here",
"emoji": true
},
"url": "https://mycompany.com/link2"
}
}
]
}]
}
For this aim, I've used JSONObject and JSONArray (org.json). Here is the particular section of this JSON which must be dynamic and extendable.
{
"type":"section",
"text":{
"type":"mrkdwn",
"text":"Test text 03"
},
"accessory":{
"type":"button",
"text":{
"type":"plain_text",
"text":"Click Here",
"emoji":true
},
"url":"https://mycompany.com/link3"
}
}
The problem is, merging/appending two JSONObjects together is not possible without defining the 'key'. How can I add the dynamic part to the JSON.
private JSONObject produceJsonBlock(final List<String> links) {
JSONObject jsonObject = new JSONObject()
.put("channel", "channelId")
.put("thread_ts", "threadId")
.put("reply_broadcast", "broadcast")
.put("attachments", new JSONArray()
.put(0, new JSONObject()
.put("color", "colorMessage")
.put("blocks", new JSONArray()
.put(0, new JSONObject()
.put("type", "divider")
.put("type", "section")
.put("text", new JSONObject()
.put("type", "mrkdwn")
.put("text", "")
)
.put("type", "divider")
)
)
)
)
links.each { final String link ->
JSONObject linksJson = new JSONObject()
.put("type", "section")
.put("text", new JSONObject()
.put("type", "mrkdwn")
.put("text", "Test text ...")
)
.put("accessory", new JSONObject()
.put("type", "button")
.put("text", "Click Here")
.put("emoji", true)
.put("url", "https://mycompany.com/${link}")
)
/**
* ???
* As I checked jsonObject.append()/jsonObject.put(), they cannot be used. because
* they don't accept just a JSONObject without introducing the key.
* */
}
}