Home > front end >  Preparing JSON array of Objects from multiple array list
Preparing JSON array of Objects from multiple array list

Time:07-06

I am very new to the Groovy scripts and would like to build a JSON output from the below JSON input. Kindly help!

My JSON input looks like this:

{
  "id":"1222",
  "storageNode": {
    "uuid": "22255566336",
    "properties": {
      "BuinessUnit": [
        "Light",
        "Fan",
        "Watch"
        ],
      "Contact": [
        "[email protected]",
        "[email protected]"
        ],
      "Location": [
        "Banglore",
        "Surat",
        "Pune"
        ]
    }
  }
}

Expected Output:

[
{
  "BuinessUnit": "Light",
  "Contact": "[email protected]",
  "Location": "Banglore"
},
{
  "BuinessUnit": "Fan",
  "Contact": "[email protected]",
  "Location": "Surat"
},
{
  "BuinessUnit": "Watch",
  "Contact": "",
  "Location": "Pune"
}
]

Please note that in case any array is not matching the value count that will always be the last one and in that case, a blank value ("") has to be populated. The "BusinessUnit" object can be referred for array size validation.

My code looks like this:

import com.sap.gateway.ip.core.customdev.util.Message;
import java.util.HashMap;
import groovy.json.*;


def Message processData(Message message) {    
    //Body 
    def body = message.getBody(String.class);    
    def jsonSlurper = new JsonSlurper()
    def list = jsonSlurper.parseText(body)
    String temp


    def BU = list.storageNode.properties.get("BusinessUnit")

    def builder = new JsonBuilder(
        BU.collect {
            [
                BusinessUnit: it
                
            ]
        }
    )
    message.setBody(builder.toPrettyString())
    return message
}

It is only returning this:

[
    {
        "BusinessUnit": "Light"
    },
    {
        "BusinessUnit": "Fan"
    },
    {
        "BusinessUnit": "Watch"
    }
]

Now how will I add other parts to it? Please help!

CodePudding user response:

I have come up with the following solution that converts source JSON string to the target JSON string:

import groovy.json.JsonBuilder
import groovy.json.JsonSlurper

def json = '''
{
  "id":"1222",
  "storageNode": {
    "uuid": "22255566336",
    "properties": {
      "BusinessUnit": [
        "Light",
        "Fan",
        "Watch"
        ],
      "Contact": [
        "[email protected]",
        "[email protected]"
        ],
      "Location": [
        "Banglore",
        "Surat",
        "Pune"
        ]
    }
  }
}
'''

println convert(json)

String convert(String json) {
    def list = new JsonSlurper().parseText(json)
    List<String> units = list.storageNode.properties.BusinessUnit
    List<String> contacts = list.storageNode.properties.Contact
    List<String> locations = list.storageNode.properties.Location
    def result = []
    units.eachWithIndex { unit, int index ->
        result << [
            BusinessUnit: unit,
            Contact     : contacts.size() > index ? contacts[index] : '',
            Location    : locations.size() > index ? locations[index] : '',
        ]
    }
    return new JsonBuilder(result).toPrettyString()
}

I've omitted the logic of getting string from the message and packaging transformed JSON into message. I hope it will help you to move forward. Please let me know if you need further assistance here.

CodePudding user response:

You can use the built-in Groovy facilities, like transpose():

import groovy.json.*

def json = new JsonSlurper().parseText '''{   "id":"1222",   "storageNode": {     "uuid": "22255566336",     "properties": {       
   "BuinessUnit": [         "Light",         "Fan",         "Watch"         ],      
   "Contact": [         "[email protected]",         "[email protected]"         ],       
   "Location": [         "Banglore",         "Surat",         "Pune"         ]     }   } }'''

def names = json.storageNode.properties*.key
def values = json.storageNode.properties*.value

int maxSize = values*.size().max()
// pad lists with trainiling spaces
values.each{ v -> ( maxSize - v.size() ).times{ v << '' } }

def result = values.transpose().collect{ tuple -> [ names, tuple ].transpose().collectEntries{ it } }

assert result.toString() == '[[BuinessUnit:Light, Contact:[email protected], Location:Banglore], [BuinessUnit:Fan, Contact:[email protected], Location:Surat], [BuinessUnit:Watch, Contact:, Location:Pune]]'

This piece of code can process everything under storageNode.properties.

  • Related