我在JSON请求中绑定了一个层次结构的三个级别:
Group -> Zone -> Segment
(1) -> (n) -> (n)
在我的命令对象中,我有:
class GroupCommand {
Long id
Set zones
}
当绑定JSON请求时,区域被正确绑定,我得到一个LinkedHashSet,我可以获取其属性并与我的域对象一起使用。但是,当我在我的服务中迭代片段时:
groupCommand.zones.each { zone ->
zone.segments.each { segment ->
//Would like to get LinkedHashMap here also
//but get JSONArray
}
}
如上所述,我理想情况下深度嵌套的Segments也会绑定到LinkedHashMap,但它绑定到JSONArray。
有关如何将其绑定到LinkedHashMap的任何建议,因为我希望避免在我的服务中操作JSONArray,从而将我的服务与JSON格式耦合。
如果有一种方法可以使用getter在命令级别进行转换,我也都是这样。
感谢
编辑:
使用
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
似乎有效,但底层对象仍然是JSON元素。然后我尝试使用:
List<RateZoneCommand> zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
并且至少我收到错误,表明它正在尝试转换:
Validation error: ... org.codehaus.groovy.grails.web.json.JSONArray to required type java.util.List for property zones; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org..JSONObject] to required type [ZoneCommand] for property zones[0]: no matching editors or conversion strategy found.
答案 0 :(得分:2)
为每个级别创建一个命令类。将Zone
- 和Segment
- 命令标记为@Validateable
。
到GroupCommand
添加:
List zones = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(ZoneCommand.class))
到ZoneCommand
添加:
List segments = org.apache.commons.collections.list.LazyList.decorate(new ArrayList(), new org.apache.commons.collections.functors.InstantiateFactory(SegmentCommand.class))
在您的表单中使用group.zones[0].segments[0]
。如果更改命令类的字段类型,请记住重新启动grails服务器。