How can I check for a key in json, which I am getting as an output from RESTful api

Amy picture Amy · Jul 8, 2013 · Viewed 13.9k times · Source

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.

Answer

tim_yates picture tim_yates · Jul 8, 2013

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' ) ) {