Groovy:实施 JsonSlurper 会产生 JsonException --- 通常有效

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

我正在尝试在 SoapUI 中构建一个 json 请求并尝试 post 到一个测试步骤。为了构建请求,我有以下代码。当我执行它时,它抛出一个 JsonException(下面提供的文本。)任何建议将不胜感激。我已经为 60 多个服务完成了此操作(所以我已经完成了 1001 次)并且所有服务都有 passed/worked。我无法确定这里的问题是什么。谢谢!

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
}

异常:

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

我也使用了下面的代码来解析,但这会引发不同类型的异常(不是那种映射)并且不允许我将值设置为键。

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

你的JSON中有non-breaking space character(s),很遗憾无效,应该是通常的space字符。

使用 LAX 模式是个好主意,但它似乎无法处理非中断 spaces:

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

所以如果你不能在源头清理你的数据,你可以这样过滤它:

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

看起来你的脚本有一些小问题。

下面的脚本:

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 ]

    println "REQUEST JSON SLURP: " + jsonReq
    return jsonReq
}
​setReqPayload([1,2,3,4,5,6])​

产生以下输出:

{actDate=4, coInfo={coType=5, secId=6}, dirIndicator=2, objectId=1, selectActId=3}