Below is my attempt to learn and apply functional programming using json mapping as example. Will see how far I can go and accomplish when using functional programming, compare to procedural programming that I familiar with.

Transform Flat Json to Nested Json using JsonSlurper, groupBy, collect, sort and JsonBuilder

This example do mapping from source json to target json, group by OrderID, ProductID, and sorted descending by OrderID. When JsonSlurper read json payload, sourceJson is Groovy Map. then construct targetJson nested Map, and finally pass nested Map to JsonBuilder to output final target json payload.

Source Json:

Target Json:

Extract summary and total using inject

This example show usage of inject function, it is similar to fold/reduce in other functional programming language. Basically it accept collection, accumulate all result from right side of function and return as final result.

Source Json:

Target Json:

Filter Json array by conditions using findAll and curry

Filter by condition with example below:

Source Json:

Target Json

Recursive traverse nested Json and apply transformation based on condition

goDeep function will recursively traverse all json node, and will apply transformation using higher order function(HOF) passed via parameter doSomething. The transformation is apply on the value of json, not on the key.

Since goDeep recursive traversal is same for different transformation, so to reuse goDeep, pass below list of HOF to goDeep function to have different transformation:
toUpperCase will convert string value to upper case.
nullToEmpty will convert all null value become empty string.
trimLeftRight will trim string value.
leftPadZeroIfKeyMatched will left pad zero on value based on matching key and number of characters set.
leftPadZeroIfKeyId using curry to left pad zero with total 5 chars when key = id
leftPadZeroIfKeyQty using curry to left pad zero with total 8 chars when key = qty

Using above convention, is flexible to build other functions that do different transformation, while still reuse goDeep recursive traversal. Recursive traversal is especially useful if the source json payload’s structure is not fixed, unknown in advance, or is impossible or too cumbersome to identify all required fields that need transformation, so let recursive do it work, apply necessary transformation when condition is met regardless of how deep the json structure.

Source Json:

Target Json:

Groovy – Json Mapping with Functional Programming Example
Tagged on:                                 

Leave a Reply

Your email address will not be published. Required fields are marked *