Worst Practice: editing JSON with regex

One of the fundamental tenets of building a large managed app is that all of your developers should of course work outside of the packaging org until it’s time to actually release. Normally the features built into apex around implicitly preferring your app’s namespace handle this for you: [SELECT field__c FORM Obj__c] works with or without being in the namespaced org (the only place the namespace prefix applies).

However when you start building rich client applications this gets much more complex, as the JSON serializer always includes the namespace prefix. If you build a client app to expect field__c and it finds ns__field__c in the response you’re going to have an especially bad day when it comes to post-packaging testing.

You can try and serialize the JSON yourself, removing the namespace prefix from any keys as needed, but this requires some dramatic shifts in how your apex works, and precludes using many of the built-in features of JSON.serialize.

Enter regex. While not documented explicitly it’s been said before that String.replaceAll invokes the underlying java implementation, which happens to not only support regex, but regex with capture groups.

With a bit of care you can build a regex that will only match JSON keys, and further only keys that start with your namespace prefix (so as to allow other managed fields to be included without clobbering yours), something like ([a-zA-Z0-9_-]+":) - worth noting this won’t match all valid JSON due to the lack of handling whitespace before the colon. However the apex JSON.serialize method’s results will consistently match with this.

Combining the two tricks leads us to some code along the lines of:



Whatever Object (subject in the sample code), or collections of Object are serialized will automatically have any and all namespace prefixes removed by that regex. A neat trick, especially when like me you discover this particular hurdle late in the development cycle.