JSON中的Grails allErrors

JSON中的Grails allErrors,json,grails,Json,Grails,如何在呈现的JSON中包含errors.allErrors 我希望我的JSON看起来像这样: {id:10 name:"" _errors: [{name:"Name cannot be blank"}], children: [{field:"value", _errors:[]}, ...] } 等 因此,当使用像Angular这样的东西时,我们的错误与字段在同一个“类”中。当您有一个复杂的树时,在另一个映射中返回错误是不起作用的。在grails中获取漂亮JSON的最简单方法

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

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

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


因此,当使用像Angular这样的东西时,我们的错误与字段在同一个“类”中。当您有一个复杂的树时,在另一个映射中返回错误是不起作用的。

在grails中获取漂亮JSON的最简单方法是从映射,因此:

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

只有当你放弃时,你才能找到答案

Grails总是用Marshallers插件()来覆盖它

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

static marshalling={
    json{
        angular{    
            virtual {
                _errors {value, json ->                     
                    json.value (com.ocom.grails.ErrorsMap.generateMap(value));          
                }
            }
        }
    }
}
其中com.ocom.grails.ErrorsMap.generateMap(value)将接受域类并返回一个错误数组

在控制器中,按如下方式返回JSON

render JSON.use('angular') {responseJson as JSON}
这适用于Grails2.3.11