Groovy: validate JSON string

后端 未结 3 1782
天命终不由人
天命终不由人 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:06

    can validate like this:

    assert JsonOutput.toJson(new JsonSlurper().parseText(myString)).replaceAll("\\s", "") ==
                myString.replaceAll("\\s", "")
    

    or a bit cleaner:

    String.metaClass.isJson << { ->
        def normalize = { it.replaceAll("\\s", "") }
    
        try {
            normalize(delegate) == normalize(JsonOutput.toJson(new JsonSlurper().parseText(delegate)))
        } catch (e) {
            false
        }
    }
    
    assert '{"key":"value"}'.isJson()
    assert !''.isJson()
    

提交回复
热议问题