Grails JSON array

后端 未结 4 2173
遇见更好的自我
遇见更好的自我 2021-02-08 03:18

I\'m converting a list of Foo objects to a JSON string. I need to parse the JSON string back into a list of Foos. However in the following example, parsing gives me a list of JS

4条回答
  •  爱一瞬间的悲伤
    2021-02-08 03:45

    I've taken this code and extended it to work with nested structures. It relies on a 'class' attribute existing in the JSON. If there's a better way by now in Grails please let me know.

         // The default JSON parser just creates generic JSON objects.  If there are nested
    
        // JSON arrays they are not converted to theirs types but are left as JSON objects
        // This converts nested JSON structures into their types.
        // IT RELIES ON A PROPERTY 'class' that must exist in the JSON tags
        JSON.metaClass.static.parseJSONToTyped = {def jsonObjects ->
    
            def typedObjects = jsonObjects.collect {JSONObject jsonObject ->
                if(!jsonObject.has("class")){
                    throw new Exception("JSON parsing failed due to the 'class' attribute missing: " + jsonObject)
                }
    
                def targetClass = grailsApplication.classLoader.loadClass(jsonObject.get("class"))
                def targetInstance = targetClass.newInstance()
    
                // Set the properties of targetInstance
                jsonObject.entrySet().each {entry ->
                    // If the entry is an array then recurse
                    if(entry.value instanceof org.codehaus.groovy.grails.web.json.JSONArray){
                        def typedSubObjects = parseJSONToTyped(entry.value)
                        targetInstance."$entry.key" = typedSubObjects
                    }
                    else if (entry.key != "class") {
                        targetInstance."$entry.key" = entry.value
                    }
                }
    
                targetInstance
            }
    
            return typedObjects
        }
    

提交回复
热议问题