在grails中构建完整的JSON

时间:2013-05-22 05:45:39

标签: 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
       {
         result = "..."
       }
       render result as JSON
    }

 }

我想要的JSON应该是这样的:

成功的JSON

{
   "meta": {
      "status": 200,
      "msg": "OK"
   },
   "response": {
      "color": {
         "colorname": "Red",
         "shade": "light
      }
   }
}

回复不成功:

{
   "meta": {
      "status": 400,
      "msg": "Something went worn"
   },
   "response": {
      "color": {
      }
   }
}

问题

如何在返回json时修改控制器操作以解决这两种情况?

1 个答案:

答案 0 :(得分:0)

成功回复:

{
"meta": {
  "status": 200,
  "msg": "OK"
},
"response": {
  "color": {
     "colorname": "Red",
     "shade": "light
  }
}
}

使用:

result = [meta: [status: '200', msg: 'OK'], response:[color:[colorname: color.name, colorshde: color.shade] ] ]

对于不成功的回复:

{
  "meta": {
  "status": 400,
  "msg": "Something went worn"
},
"response": {
  "color": {
  }
}
}

使用

 result = [meta: [status: '400', msg: 'wrong'], response:[color:[] ] ]