Skip to Content
0
Aug 03, 2020 at 05:44 PM

Groovy script to format JSON

1003 Views Last edit Aug 03, 2020 at 05:45 PM 2 rev

Hello Experts,

I have a JSON payload in following format...

{
    "root": {
        "teams": [
            {
                "VisitFrequencyPerYear": "0",
                "UPI": "422511",
                "complete": "false"
            },
            {
                "VisitFrequencyPerYear": "0",
                "UPI": "421802",
                "complete": "false"
            }
        ]
    }
}

But I need it in following format:

 [
            {
                "VisitFrequencyPerYear": "0",
                "UPI": "422511",
                "complete": "false"
            },
            {
                "VisitFrequencyPerYear": "0",
                "UPI": "421802",
                "complete": "false"
            }
 ]

To achieve this, I'm using the following Groovy script:

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

def Message processData(Message message) {
    
    def body = message.getBody();
    body = body.substring(body.indexOf('\n')+19);
  
    def json_to_str=body.substring(1,body.length()-3);  
    message.setBody(json_to_str);
    
    return message;
}

But I'm receiving error messages like:

Error at line: 7
***
org.codehaus.groovy.runtime.InvokerInvocationException: groovy.lang.MissingMethodException: No signature of method: java.io.ByteArrayInputStream.indexOf() is applicable for argument types: (String) values: [
]
Possible solutions: inject(groovy.lang.Closure), findIndexOf(groovy.lang.Closure)
    at com.groovyide.ExecutorService$1.run(ExecutorService.java:84)

Could someone please suggest what I'm doing wrong here?

Thank you for your support.

Regards,

Anirban Mallick