You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Grails 4 JSON视图如何将Map类型属性渲染为JSON嵌套子对象

错误原因

Grails 4 JSON 视图的默认序列化逻辑无法直接处理Map<String, 领域类>这类结构,直接传递Map给JSON节点会触发递归序列化死循环,最终抛出StackOverflowError栈溢出错误。

解决方案

修改/foo/_foo.gson模板的mealsByPerson节点渲染逻辑,手动遍历Map构造JSON结构,同时保留自定义渲染的灵活性:

import rendermapexample.Breakfast

model {
    Float cost
    Date date
    Map<String, Breakfast> mealsByPerson
}

json {
    date date
    cost cost
    // 手动遍历Map构建子节点
    mealsByPerson {
        mealsByPerson.each { String personName, Breakfast breakfast ->
            // 动态生成Map键对应的JSON属性
            "${personName}" {
                eggs breakfast.eggs
                meat breakfast.meat
                side breakfast.side
                // 可在此灵活添加自定义渲染逻辑,比如字段重命名、值转换、嵌套其他字段等
            }
        }
    }
}

如果不需要对每个Breakfast对象的字段做单独定制,也可以使用内置渲染方法简化写法:

json {
    date date
    cost cost
    mealsByPerson g.render(mealsByPerson)
}

两种写法都可以输出预期的JSON结构,且保留了JSON视图的自定义渲染能力,完全满足复杂业务场景的定制需求。


内容的提问来源于stack exchange,提问作者SGT Grumpy Pants

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:12:02