How to return array values from a JSON String array

How to return array values from a JSON String array

book

Article ID: KB0078757

calendar_today

Updated On:

Products Versions
TIBCO BusinessEvents Enterprise Edition 5.5.0

Description

To return each value from JSON string array you can loop throw node elements and check for the key.

eg:
JSON String:
{"MainNode": {"ArrayNode": [{"retValue": "Error_1","message": "No data"},{"retValue": "Error_2","message": "Data incomplete"}],"retValue": "NOT_OK"}}";    

A Rulefunction should return a String array that includes all "retValues" of json node "ArrayNode". In sample RuleFunction returns "String[]{"Error_1","Error_2"}".

Issue/Introduction

Usage of JSON catalog functions

Environment

All Operating Systems

Resolution

This is a sample only with a hardcoded JSON String.

1.) Add Rulefunction below to your project
//=====================================================================================
String[] rulefunction RuleFunctions.rfJsonRetAllArrayCodeElementsUsingArrayList {
    scope {
        String pjsonStr;
        String pjsonNodename;
        String pjsonElement;
    }
    body {
    
    Object jsonNode = JSON.parseJSON(pjsonStr);
    Object jsonNodeError =JSON.findValueNode(jsonNode,pjsonNodename);
    Object itJsonFields = JSON.getAllElements(jsonNodeError);
    int i=0;
    Object oValueList=Collections.List.createArrayList();
    while(Collections.Iterator.hasNext(itJsonFields)) {
        Object element = Collections.Iterator.next(itJsonFields);
        Object fieldMap = JSON.getFields(element);
        while(Collections.Iterator.hasNext(fieldMap))
        {
            Object fieldEntry = Collections.Iterator.next(fieldMap);
               //System.debugOut("### " + Collections.Map.Entry.getKey(fieldEntry) + " :" + Collections.Map.Entry.getValue(fieldEntry));
               
            if (Collections.Map.Entry.getKey(fieldEntry)==pjsonElement) {
                   System.debugOut("### Array node " + pjsonNodename + "found value for element "+ pjsonElement + "=" + Collections.Map.Entry.getValue(fieldEntry));
                   Collections.List.add(oValueList,i,Collections.Map.Entry.getValue(fieldEntry));
                   i++;    
            }
        }    
     }    
     
     String[] sArrRet=String[i]{};
     for (int iCnt=0;iCnt<i;iCnt++) 
         sArrRet[iCnt]=Collections.List.get(oValueList,iCnt);
     
     return sArrRet;    
    }
}
//=====================================================================================


2.)
To test the RuleFunction add code below to one of your Rules/Rulefunctions.
 
String jsonStr="{\"MainNode\": {\"ArrayNode\": [{\"retValue\": \"Error_1\",\"message\": \"No data\"},{\"retValue\": \"Error_2\",\"message\": \"Data incomplete\"}],\"retValue\": \"NOT_OK\"}}";    
String[] sRet = RuleFunctions.rfJsonRetAllArrayCodeElementsUsingArrayList(jsonStr,"ArrayNode","retValue");

Additional Information

JSON, catalog functions