0

我有一个看起来像这样的类:

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 确认)。现在只有itemin的属性Foo.constraints会被添加到cellfor flexigrid 中。

4

2 回答 2

2

我认为不能foo.getProperties()保证订购的任何内容。但是Foo.constraints在运行时被覆盖以返回不是原始闭包,而是一个对象和此映射中的键Map保证约束闭包的顺序相同(这就是脚手架能够使用约束排序来定义顺序的方式其中字段显示在脚手架视图中)。所以你可以做类似的事情ConstrainedProperty

def props = [:] // [:] declares a LinkedHashMap, so order-preserving
Foo.constraints.each { k, v ->
  props[k] = foo."${k}"
}
于 2012-06-22T11:35:33.243 回答
0

foo.getProperties().sort()或者,如果没有按您需要的顺序对属性进行排序的好方法,您始终可以自己在列表中定义属性的顺序以进行迭代。

def properties = ['name', 'description']
properties.each {
     cell.add(foo."$it")
}
于 2012-06-22T05:23:56.680 回答