JSON 中的 Grails allErrors

Grails allErrors in JSON

如何在呈现的 JSON 中包含 errors.allErrors?

我希望我的 JSON 看起来像这样:

{id:10
 name:""
  _errors: [{name:"Name cannot be blank"}], 
  children: [{field:"value", _errors:[]}, ...] 
}

等等

因此,当使用 Angular 之类的内容时,我们会在与字段相同的 "class" 中遇到错误。当你有一个复杂的树时,在另一个地图中返回错误不起作用。

在 grails 中获得漂亮 JSON 的最简单方法是来自 MAP,因此:

[id:10,
 name:"",
 _errors: [name:"Name cannot be blank"], 
 children: [field:"value", _errors:[], ...] 
] as grails.converters.JSON

只有在放弃的时候才能找到答案。

Grails 一如既往地使用 Marshallers 插件 (https://grails.org/plugin/marshallers)

添加插件,然后将以下内容添加到域 Class

static marshalling={
    json{
        angular{    
            virtual {
                _errors {value, json ->                     
                    json.value (com.ocom.grails.ErrorsMap.generateMap(value));          
                }
            }
        }
    }
}

其中 com.ocom.grails.ErrorsMap.generateMap(value) 将采用域 class 和 return 错误数组

在控制器中 return JSON 像这样

render JSON.use('angular') {responseJson as JSON}

这适用于 Grails 2.3.11