使用 gson Grails 视图序列化地图<FooCategory, List<Foo>>
Serialize a Map<FooCategory, List<Foo>> using gson Grails view
我们的后端正在构建一个 FooCategory
作为键的映射,值是 Foo
元素的列表。由于控制器将此添加到 json
渲染过程的模型中,因此 Grails gson
文件如下所示:
model {
List<String> names
Map<FooCategory, List<Foo>> categories
}
json {
names names
categories <<what is the syntax>>
}
经过多次试验,我实际上无法获得对 Foo 元素列表的有效引用。例如,我想像这样生成 json
输出:
{
"names": ["name1", "name2"],
"categories": [
{
"name": "category_1",
"fooCount": 5
},
{
"name": "category_5",
"fooCount": 8
}
]
}
下一步是使用 tmpl.templateName(fooElements)
语法将 Foo
元素列表传递给模板,但现在我只是停滞在 count 属性上。任何帮助表示赞赏!
我发现 Grails 的视图使用 tmpl
处理可迭代实体,但由于 Map 不可迭代,我们必须显式调用 entrySet()
方法。这是一个工作版本:
model {
List<String> names
Map<FooCategory, List<Foo>> categories
}
json {
def stats = categories.entrySet().collect { cat ->
[ name: cat.key.name, fooCount: cat.value.size() ]
}
names names
categories stats
}
现在可以将 Iterable (categories.entrySet()
) 传递给如下所示的模板:
model {
Map.Entry<FooCategory, List<Foo>> entry
}
json {
FooCategory fooCategory = entry.key
List fooElements = entry.value
...
}
我们的后端正在构建一个 FooCategory
作为键的映射,值是 Foo
元素的列表。由于控制器将此添加到 json
渲染过程的模型中,因此 Grails gson
文件如下所示:
model {
List<String> names
Map<FooCategory, List<Foo>> categories
}
json {
names names
categories <<what is the syntax>>
}
经过多次试验,我实际上无法获得对 Foo 元素列表的有效引用。例如,我想像这样生成 json
输出:
{
"names": ["name1", "name2"],
"categories": [
{
"name": "category_1",
"fooCount": 5
},
{
"name": "category_5",
"fooCount": 8
}
]
}
下一步是使用 tmpl.templateName(fooElements)
语法将 Foo
元素列表传递给模板,但现在我只是停滞在 count 属性上。任何帮助表示赞赏!
我发现 Grails 的视图使用 tmpl
处理可迭代实体,但由于 Map 不可迭代,我们必须显式调用 entrySet()
方法。这是一个工作版本:
model {
List<String> names
Map<FooCategory, List<Foo>> categories
}
json {
def stats = categories.entrySet().collect { cat ->
[ name: cat.key.name, fooCount: cat.value.size() ]
}
names names
categories stats
}
现在可以将 Iterable (categories.entrySet()
) 传递给如下所示的模板:
model {
Map.Entry<FooCategory, List<Foo>> entry
}
json {
FooCategory fooCategory = entry.key
List fooElements = entry.value
...
}