Groovy:实现JsonSlurper会给出一个JsonException ---通常可行

时间:2017-05-25 19:41:49

标签: parsing groovy soapui jsonslurper

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

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

2 个答案:

答案 0 :(得分:0)

你的JSON中有non-breaking space character(s),不幸的是它无效,应该是通常的空格字符。

使用LAX模式是一个好主意,但它似乎没有处理不间断的空格:

  

如果要启用宽松的JSON解析,请使用LAX,即允许   评论,没有引用字符串等。

因此,如果您无法在源头清理数据,可以按照以下方式对其进行过滤:

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

答案 1 :(得分:0)

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

脚本下方:

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}