我在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.
为每个级别创建一个命令类。将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服务器。