移动到src / groovy时,Grails JSON转换器和JSONObject代码会中断

时间:2014-08-20 19:19:39

标签: json grails

我正在尝试将一些代码从grails服务文件移到src / groovy中以便更好地重用。

import grails.converters.JSON
import org.codehaus.groovy.grails.web.json.JSONObject

class JsonUtils {

    // seems like a clunky way to accomplish converting a domainObject
    // to its json api like object, but couldn't find anything better.
    def jsonify(obj, ArrayList removeableKeys = []) {
        def theJson = obj as JSON
        def reParsedJson = JSON.parse(theJson.toString())
        removeableKeys.each { reParsedJson.remove(it) }
        return reParsedJson
    }

    // essentially just turns nested JSONObject.Null things into java null things
    // which don't get choked on down the road so much.
    def cleanJson(json) {
        if (json instanceof List) {
            json = json.collect(cleanJsonList)
        } else if (json instanceof Map) {
            json = json.collectEntries(cleanJsonMap)
        }
        return json
    }

    private def cleanJsonList = {
        if (it instanceof List) {
            it.collect(cleanJsonList)
        } else if (it instanceof Map) {
            it.collectEntries(cleanJsonMap)
        } else {
            (it.class == JSONObject.Null) ? null : it
        }
    }

    private def cleanJsonMap = { key, value ->
        if (value instanceof List) {
            [key, value.collect(cleanJsonList)]
        } else if (value instanceof Map) {
            [key, value.collectEntries(cleanJsonMap)]
        } else {
            [key, (value.class == JSONObject.Null) ? null : value]
        }
    }

}

但是当我尝试从服务中调用jsonifycleanJson时,我得到了MissingMethodExceptions

来自grails服务文件的示例调用:

def animal = Animal.read(params.animal_id)
if (animal) json.animal = JsonUtils.jsonify(animal, ['tests','vaccinations','label'])

错误:

No signature of method: static org.JsonUtils.jsonify() is applicable for argument types: (org.Animal, java.util.ArrayList) values: [ ...]]\ Possible solutions: jsonify(java.lang.Object, java.util.ArrayList), jsonify(java.lang.Object), notify()

还尝试让jsonify拍摄动物jsonify(Animal obj, ...)然后它只是说Possible solutions: jsonify(org.Animal, ...

cleanJson方法是为了处理JSONObject.Null以前给我们带来问题的东西。

示例电话:

def safeJson = JsonUtils.cleanJson(json) // json is request.JSON from the controller

错误:

groovy.lang.MissingMethodException: No signature of method: static org.JsonUtils.cleanJson() is applicable for argument types: (org.codehaus.groovy.grails.web.json.JSONObject) values: [[...]]
Possible solutions: cleanJson(org.codehaus.groovy.grails.web.json.JSONObject)

所有这些代码都在服务文件中工作。我正在运行grails 2.3.11 BTW

2 个答案:

答案 0 :(得分:1)

您已将jsonify()cleanJson()声明为实例方法,并尝试将它们用作静态。将它们声明为静态,它应该起作用:

class JsonUtils {

    def static jsonify(obj, ArrayList removeableKeys = []) {
       (...)
    }

    def static cleanJson(json) {
        (...)
    }
}

答案 1 :(得分:1)

您需要将jsonify()cleanJson()定义为static才能静态调用它们。