Search code examples
parsinggroovysoapuijsonslurper

Groovy: Implementing JsonSlurper is giving a JsonException --- Usually works


I am trying to build a json request in SoapUI and trying to post to a test step. For building the request, I have below code. When I execute it, it is throwing a JsonException (text provided below.) Any advise would be greatly appreciated. I have done this for over 60 services (so I've done this a 1001 times) and all of them have passed/worked. I am unable to pinpoint as to what the issue here is. Thanks!

import groovy.json.JsonSlurper
import groovy.json.JsonOutput

def setReqPayload ( pArrKeyValues ) {//[objId, dirInd, selActId, actDt, coType, secId]
    def jsonPayload = '''   
    {
        "objectId" : "",
        "actDate": "",
        "dirIndicator" : "",
        "selectActId" : "",
        "coInfo" : {"secId" : "","coType" : ""}
    }
    '''
    // parse the request
    def jsonReq = new JsonSlurper ( ).parseText ( jsonPayload )

    jsonReq.objectId        = pArrKeyValues [ 0 ] )             
    jsonReq.dirIndicator    = pArrKeyValues [ 1 ]
    jsonReq.selectActId     = pArrKeyValues [ 2 ]
    jsonReq.actDate         = pArrKeyValues [ 3 ]
    jsonReq.coInfo.coType   = pArrKeyValues [ 4 ]
    jsonReq.coInfo.secId    = pArrKeyValues [ 5 ]

    log.info "REQUEST JSON SLURP: " + jsonReq
    return jsonReq
}

Exception:

ERROR:groovy.json.JsonException: expecting '}' or ',' but got current char ' ' with an int value of 160 The current character read is ' ' with an int value of 160

I have used below code as well to parse but that is throwing different kind of exception (Not that kind of map) and not allowing me to set the values to the keys.

// parse the request
def parser = new JsonSlurper ( ).setType ( JsonParserType.LAX )
def jsonReq = JsonOutput.toJson ( parser.parseText ( jsonPayload ) )

Solution

  • You have non-breaking space character(s) in your JSON, it's unfortunately invalid, it should be the usual space character.

    Using LAX mode was a good idea but it does not seem to handle non-breaking spaces:

    Use LAX if you want to enable relaxed JSON parsing, i.e., allow comments, no quote strings, etc.

    So if you cannot clean up your data at the source, you can filter it like this:

    jsonPayload = jsonPayload.replace('\u00a0', '\u0020')