Preview Request/Response body in JSON format using Visualforce page
While working on third party REST API integrations with Salesforce, figuring out request and response payloads was very tedious and I found extremely difficult to understand the payload structure from the debug logs as they saved in string format
(usually long string) and the matter of fact would be they are in unreadable format so I left with no other option other than copy/pasting the JSON data in my IDE (VS Code) or some online JSON formatter to get the payload structure which made so frustrated because I need to lookup for so many logs then need to copy/paste carefully by selecting all characters, you know while copying sometimes you can get some extra character copied or we need to remove unnecessary items and it goes on...
Now you might get an idea of what I'm trying to solve here, which is to eliminate manual copy/paste job with the help of Visualforce page which helps you view JSON data/payload in prettified format so that now you can focus to fix the actual issue rather than spending lots of time in copy/paste job.
This solution works only when you're saving request & response in a custom object
When I decided to fix this problem with the help of Visualforce page, then I thought to write it in a generic way so that it can be used for any sObject that has JSON data information.
I solved above problem by utilizing a Visualforce page and a controller (Apex Class) where it accepts two query string parameters viz.,
Id
- Record Id of the objectfield
- field api name where you saved JSON data
This is how the url looks like /apex/jsonPreview?id=record-id&field=field-api
Now you have the full control of the above page to make it actionable for e.g., I can add this as a formula field of the url type as shown below
HYPERLINK('/apex/jsonPreview?field=JSON_Payload__c&id='+Id,'JSON Preview', '_blank')
Note: we also need sObject name here, but we are going to fetch it dynamically in Apex class
Repository links
HINTS
- If you're previewing from developer console try to remove the unnecessary query parameters if you're facing any issue
- You cannot write any code either JavaScript or HTML in Visualforce because as we're rendering it as
JavaScript app
it will treat everything as text