Forum Discussion

ngoj's avatar
ngoj
New Contributor
7 years ago

REST - JSON request

Here's a sample JSON request:  Sample1 comes with an attribute Type and it's empty. Is it possible if the attribute is empty. Can this be removed like the output on sample2. I tried to use the remove empty content and set it true which I usually did on XML. However, it seems like this does not apply do JSON request message.  I am not sure if there's a way around this.

 

Sample 1:

        "Transfer" : {
            "Service" : "Mix",
            "Instruct" : {
                "Account" : {
                    "Number" : "xx8172121",
                    "Type" : "",
                    "Prod": "NEW"
                }
   }
  }   

 

Sample 2:

        "Transfer" : {
            "Service" : "Mix",
            "Instrucy" : {
                "Account" : {
                    "Number" : "xx8172121",
                    "Prod": "NEW"
                }
   }
  }   

 

 

 

  • You can do this with JsonSlurper and JsonBuilder

     

    import groovy.json.*
    
    // Deserialize JSON into generic map
    def obj = new JsonSlurper().parseText(Sample1)
    
    // Remove Type
    obj.getAt("Transfer").getAt("Instruct").getAt("Account").remove("Type")
    
    // Serialize back to Json
    String json = new JsonBuilder(obj).toString()

    This does assume that the structure of these objects will always be the same. If that is not the case, you would need to iterate the map.

    • ngoj's avatar
      ngoj
      New Contributor

      Thanks for the input. When you say Sample1 do you mean an input file or a REST (POST message ) like something shown below. As I do need to pull out data from the Excel data sheet.

       

      {
        "Transfer": {
          "Service": "${#Project#service}",
          "Instruct": {
            "Account": {
              "Number": "${#Project#Number}",
              "Type": "",
              "Prod": "${#Project#Prod}"
            }
          }
        }
      }

      • JustinM89's avatar
        JustinM89
        Contributor

        Yes, so:

         

        import groovy.json.*
        
        String sample1 = '{"Transfer": {"Service": "${#Project#service}","Instruct": {"Account": {"Number": "${#Project#Number}","Type": "","Prod": "${#Project#Prod}"}}}}'
        // Deserialize JSON into generic map def obj = new JsonSlurper().parseText(sample1) // Remove Type obj.getAt("Transfer").getAt("Instruct").getAt("Account").remove("Type") // Serialize back to Json String json = new JsonBuilder(obj).toString()

         

        Now where you get sample1 from depends on your test, whether you're pulling it from an Excel sheet or directly from the response of a REST request.