我有一个看起来像这样的类:
class Foo {
name
description
static constraints = {
name()
description()
}
}
我想在Flexigrid中添加我的类的显示实例。将数据发送到 flexigrid 时,它需要采用 JSON 或 XML 之类的格式……我选择了 JSON。Flexigrid 期望它接收到的 JSON 数组具有以下格式:
{
"page": "1",
"total": "1",
"rows": [
{
"id": "1",
"cell": [
"1",
"The name of Foo 1",
"The description of Foo 1"
]
},
{
"id": "2",
"cell": [
"2",
"The name of Foo 2",
"The description of Foo 2"
]
}
]
}
为了让我的Foo
对象变成这种格式,我做了类似的事情:
def foos = Foo.getAll( 1, 2 )
def results = [:]
results[ "page" ] = params.page
results[ "total" ] = foos.size()
results[ "rows" ] = []
for( foo in foos ) {
def cell = []
cell.add( foo.id )
foo.getProperties().each() { key, value -> // Sometimes get foo.getProperties().each() returns foo.description then foo.name instead of foo.name then foo.description as desired.
cell.add( value.toString() )
}
results[ "rows" ].add( [ "id": foo.id, "cell": cell ] )
}
render results as JSON
问题是每隔一段时间就会foo.getProperties().each()
返回,foo.description
然后foo.name
导致foo.description
被放入我的 flexigrid 的名称列中,foo.name
并被放入我的 flexigrid 的描述列中的特定行。
Foo
我尝试在域类中指定约束,以便getProperties
以正确的顺序返回,但它不起作用。 如何确保getProperties
以可预测的顺序返回属性?
这就是我解决此问题的方法:
def items = Foo.getAll()
for( item in items ) {
def cell = []
cell.add( item.id )
Foo.constraints.each() { key, value ->
def itemValue = item.getProperty( key )
if( !( itemValue instanceof Collection ) ) {
cell.add( itemValue.toString() )
}
}
}
所以Foo.constraints
得到一个约束映射,其中每个约束都是Collections$UnmodifiableMap$UnmodifiableEntrySet$UnmodifiableEntry
. 经过测试,我发现这张地图总是Foo
按照我输入它们的顺序返回我的静态约束(也由 Ian 确认)。现在只有item
in的属性Foo.constraints
会被添加到cell
for flexigrid 中。