Groovy: validate JSON string

后端 未结 3 1781
天命终不由人
天命终不由人 2021-02-20 05:36

I need to check that a string is valid JSON in Groovy. My first thought was just to send it through new JsonSlurper().parseText(myString) and, if there was no exce

3条回答
  •  温柔的废话
    2021-02-20 06:13

    seems to be a bug or feature in groovy json parser

    try another json parser

    i'm using snakeyaml cause it supports json and yaml, but you can find other java-based json parser libraries over the internet

    @Grab(group='org.yaml', module='snakeyaml', version='1.19')
    
    def jsonString = '''{"a":1,"b":2}...'''
    
    //no error in the next line
    def json1 = new groovy.json.JsonSlurper().parseText( jsonString )
    //the following line fails
    def json2 = new org.yaml.snakeyaml.Yaml().load( jsonString )
    

提交回复
热议问题