我正在尝试将 JSON 数组接受到命令对象中。数组如下所示:
[
{prop1:'a', 'prop2:'b', prop3:'c'},
{prop1:'d', 'prop2:'e', prop3:'f'},
{prop1:'g', 'prop2:'h', prop3:'i'},
...
]
我试图通过惰性列表接受数组
class MyCommand {
List myList = ListUtils.lazyList([], FactoryUtils.instantiateFactory(Map))
}
但我收到以下错误:
InstantiateFactory: The constructor must exist and be public . Stacktrace follows:
Message: InstantiateFactory: The constructor must exist and be public
Line | Method
->> 113 | findConstructor in org.apache.commons.collections.functors.InstantiateFactory
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
| 86 | <init> in ''
| 67 | getInstance . . . in ''
| 121 | instantiateFactory in org.apache.commons.collections.FactoryUtils
接受 map 数组的正确语法是什么?
我通过
remoteFunction
发送数据像这样:var params = '{"myList":' + JSON.stringify(myList) + '}';
${remoteFunction(controller: 'myController', action: 'myAction',
params: 'params', onSuccess: 'callback(data)')};
我应该使用其他方法吗?
最佳答案
您不需要在命令对象中使用惰性列表。您可以简化代码并让内置数据绑定(bind)系统初始化 List
懒洋洋。
// grails-app/controllers/demo/DemoController.groovy
package demo
class DemoController {
def demo(MyCommand co) {
[command: co]
}
}
class MyCommand {
List<Map> data
}
您可以使用如下所示的 JSON 向该操作发送请求...
{"data": [
{prop1:'a', 'prop2:'b', prop3:'c'},
{prop1:'d', 'prop2:'e', prop3:'f'},
{prop1:'g', 'prop2:'h', prop3:'i'},
...
]}
当您这样做时,数据绑定(bind)系统将创建
MyCommand
的实例。 ,它将初始化 data
属性最初为空 List
然后将填充 List
与所有 Maps
在 JSON 中表示。该代码位于 https://github.com/jeffbrown/listofmaps 的项目中.该项目包括以下通过的测试:
// test/unit/demo/DemoControllerSpec.groovy
package demo
import grails.test.mixin.TestFor
import spock.lang.Specification
@TestFor(DemoController)
class DemoControllerSpec extends Specification {
void "test binding a List of Map to a command object"() {
when:
request.method = 'POST'
request.json = '''
{"data": [
{"prop1":"a", "prop2":"b", "prop3":"c"},
{"prop1":"d", "prop2":"e", "prop3":"f"},
{"prop1":"g", "prop2":"h", "prop3":"i"}
]
}'''
def model = controller.demo()
def command = model.command
then:
command instanceof MyCommand
command.data instanceof List
command.data.size() == 3
command.data[0] instanceof Map
command.data[0].prop1 == 'a'
command.data[0].prop2 == 'b'
command.data[0].prop3 == 'c'
command.data[1] instanceof Map
command.data[1].prop1 == 'd'
command.data[1].prop2 == 'e'
command.data[1].prop3 == 'f'
command.data[2] instanceof Map
command.data[2].prop1 == 'g'
command.data[2].prop2 == 'h'
command.data[2].prop3 == 'i'
}
}
关于grails - 如何在 Grails 中实例化惰性列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26517212/