我在 JSON 请求中绑定(bind)了层次结构的三个层次:
Group -> Zone -> Segment
(1) -> (n) -> (n)
在我的命令对象中,我有:
class GroupCommand {
Long id
Set zones
}
绑定(bind) JSON 请求时,区域会正确绑定(bind),我会得到一个 LinkedHashSet,我可以获取它的属性并与我的域对象一起使用。但是,当我开始迭代服务中的分割时:
groupCommand.zones.each { zone ->
zone.segments.each { segment ->
//Would like to get LinkedHashMap here also
//but get JSONArray
}
}
如上所述,理想情况下,我希望深度嵌套的 Segments 也绑定(bind)到 LinkedHashMap,但它绑定(bind)到 JSONArray。
任何关于如何将其绑定(bind)到 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 服务器。
关于json - grails JSON 绑定(bind)到 LinkedHashSet 而不是 JSONArray 以实现深度嵌套关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11513416/