groovy

Parse value from JSON Input message with special char format


I'm expected to read the value of where(key = Canonical message) and the value format is combination of many fields where I expected the read 'casetTitle' value in the Payload section mentioned below and set a property using JsonSlurper()

Input JsoN
    {
        "Id": "db338737-af14-ef11-9f8a-000d3aad8ef7",
        "InputParameters": [
            {
           
                "key": "CanonicalMessage",
                "value": "{\"ActivityId\":\"9f368268\",\"Payload\":{\"CaseTitle\":\"Material Description 000\",\"CustomerAssetNumber\":\"104628\"}}"
            }
            
            {
                   "key": "transactionlogid",
                    "value": "9f36828e9"
            }
        ]
        
         }

how this be achieved through using JsonSlurper()?

Thank you very much

Yours sincerely Sateesh


Solution

  • It'd look something like the following. Keep in mind I had to escape the quote escape sequence because I inlined this into a String literal. Otherwise the language was interpret \" -> " and create invalid JSON. If you were reading this from input you wouldn't need to do that. This is just an artifact of this example; not real world code.

    import groovy.json.*
    
    def slurper = new JsonSlurper()
    def json = slurper.parseText("""
       {
            "Id": "db338737-af14-ef11-9f8a-000d3aad8ef7",
            "InputParameters": [
                {
                    "key": "CanonicalMessage",
                    "value": "{\\"ActivityId\\":\\"9f368268\\",\\"Payload\\":{\\"CaseTitle\\":\\"Material Description 000\\",\\"CustomerAssetNumber\\":\\"104628\\"}}"
                },
                {
                    "key": "transactionlogid",
                    "value": "9f36828e9"
                }
            ]
            
        }
    """)
    
    List<String> caseTitles = json.InputParameters
       .findAll { it.key == "CanonicalMessage" }
       .collect { 
          def innerJson = slurper.parseText( it.value )
          innerJson.Payload.CaseTitle
       }
    
    println(caseTitles)
    
    

    This is executable and works.