2

I have a confusion here with respect to RESTful api. Code:

import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.*
import static groovyx.net.http.ContentType.JSON
import org.codehaus.groovy.grails.web.json.JSONObject


def isMailer = new HTTPBuilder( 'http://mailer-api.com' )
isMailer.request( GET, JSON ) {
        uri.path = '/is/mail/rest/json/' + token
        isMailer.auth.basic 'ddd', 'aaa'
        headers.'User-Agent' = 'Mozilla/5.0 Ubuntu/8.10 Firefox/3.0.4'
            response.success = { resp, json ->
                // response handler for a success response code:

                System.out << json

                if(json.has("DISP_NAME")) {
                    println "************************"
                    res = "Yes" 
                } else if (json.has("ListError")) {
                    res =  "No"
                }

            }
        }

        // handler for any failure status code:
        response.failure = { resp ->
            println "Unexpected error: ${resp.statusLine.statusCode} : ${resp.statusLine.reasonPhrase}"
        }
    }
    return res
}

Output w.r.t System.out << json

{
    "DISP_NAME" : "owner-atob",
    "DOM_NAME"  : "mailer",
    "GROUP_ID"  : "1229815",
    "GROUP_NAME"    : "owner-atob"
}

Error w.r.t if(json.has("DISP_NAME"))

No signature of method: org.apache.http.conn.EofSensorInputStream 
is applicable for argument types: (java.lang.String) values: [DISP_NAME]

My Problem: I want to just check if the key (which is DISP_NAME here) is present in json output. Hence, I want to differentiate my job in if-else block.

tim_yates
  • 167,322
  • 27
  • 342
  • 338
Amy
  • 51
  • 1
  • 3
  • 6

1 Answers1

15

Try replacing :

if(json.has("DISP_NAME")) {

with

if( json.DISP_NAME ) {

Of course, that won't differentiate between a NULL or empty value and a missing value.

To check the field is in the JSON object, just do:

if( json.keySet().contains( 'DISP_NAME' ) ) {
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • I tried using if( json.keySet().contains( 'DISP_NAME' ) ) it says No signature of method: org.apache.http.conn.EofSensorInputStream.keySet() is applicable for argument types: () values: [] – Amy Jul 09 '13 at 07:22
  • Might be helpful to know what version of groovy/grails you're using @Amy , may explain `No Signature` error – raffian Aug 08 '13 at 04:34
  • This is useful. I believe that Amy was saying `if (json.containsKey('DISP_NAME'))` – Rao Jun 09 '16 at 02:37