在grails中构建完整的JSON
我的控制器如下所示:在grails中构建完整的JSON,json,web-services,grails,Json,Web Services,Grails,我的控制器如下所示: def save() { js { def color = new Color(params) color.save() def result if (!color.hasErrors()) { result = [colorname: color.name, colorshde: color.shade] } else {
def save() {
js {
def color = new Color(params)
color.save()
def result
if (!color.hasErrors())
{
result = [colorname: color.name, colorshde: color.shade]
}
else
{
result = "..."
}
render result as JSON
}
}
我想要的JSON应该如下所示:
def save() {
js {
def color = new Color(params)
color.save()
def result
if (!color.hasErrors())
{
result = [colorname: color.name, colorshde: color.shade]
}
else
{
result = "..."
}
render result as JSON
}
}
成功的JSON
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"color": {
"colorname": "Red",
"shade": "light
}
}
}
未成功响应:
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"color": {
"colorname": "Red",
"shade": "light
}
}
}
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
问题
如何在返回json时修改控制器操作以考虑这两种情况?成功响应:
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"color": {
"colorname": "Red",
"shade": "light
}
}
}
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
使用:
对于未成功响应:
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
{
"meta": {
"status": 200,
"msg": "OK"
},
"response": {
"color": {
"colorname": "Red",
"shade": "light
}
}
}
{
"meta": {
"status": 400,
"msg": "Something went worn"
},
"response": {
"color": {
}
}
}
使用
嘿@Anthony,我看到了你最近的问题,你删掉了。我想说,有一种更好的方法来创建JSON响应。如果你愿意,我可以把它贴在这里作为答案?