【问题标题】:Serialize a Map<FooCategory, List<Foo>> using gson Grails view使用 gson Grails 视图序列化 Map<FooCategory, List<Foo>>
【发布时间】:2020-03-15 23:11:52
【问题描述】:

我们的后端正在构建一个 FooCategory 的 Map 作为键,值是 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 属性上。任何帮助表示赞赏!

【问题讨论】:

  • 请注意:JSON 只允许字符串键。根据 FooCategory 是什么,这可能需要考虑如何表示数据。

标签: json grails serialization groovy gson


【解决方案1】:

我发现 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

  ...
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-31
    • 1970-01-01
    • 2013-01-18
    • 2012-12-25
    • 2017-04-23
    • 2013-12-29
    相关资源
    最近更新 更多