I’ve been doing a lot of Salesforce integration as part of my most recent role. And where there’s integration, there’s JSON. The vast bulk of this work is integration using Apex, and so I began brushing up on what’s changed since I last got in the weeds many years ago. How much has changed? Surprisingly, not much!
Depending on your situation, there are broadly 3 options when it comes to handling JSON in Apex:
- Create Apex classes that are proxies of the JSON and deserialise the payloads into those structures
- Deserialise the JSON payloads into nested collections of
Map<String,Object>
- Build your own parser
The options are in order of difficulty. Additionally, options 1 and 3 make for code that is much easier to work with because the Apex Types you define are strongly typed. But option 1 isn’t always possible e.g. if the JSON you’re working with uses reserved keywords, or if you want to process part of the JSON before sticking it in an Apex structure.
However, this blog post is not about the various approaches and their pros and cons – I just wanted to provide some background. I’ve been lucky enough to have complete control over the JSON being consumed so opted for option 1. And with option 1, you need to generate Apex classes that represent the JSON you want to deserialise. I remembered a JSON2Apex tool built by the brilliant Simon Fell and Pat Patterson nearly a decade ago but suspected newer tools would’ve emerged over the past 10 years. I was right, and wrong at the same time.
The Heroku-hosted JSON2Apex seems to still be the top option but I kept wishing for additional features. Other JSON to Apex conversion tools offer some improvements, but in my testing, they break or incorrectly generate Apex for certain JSON inputs. So, I built yet another JSON to Apex converter. Or YAJAC for short.
What improvements does it make over the OG JSON to Apex tool?
- No need to download a file. The Apex output is available immediately
- It flags reserved keywords in the output Apex
- It catches basic errors in the input JSON and provides feedback on what needs to change
- It provides additional documentation on how the generated Apex can be used
As well as a few other small features that I found useful during my development work. I’m sure there are lots of other little useability features I could add, so please let me know in the comments!