2013-05-22 29 views
0

我的控制器看起來是這樣的:Grails中構建完整的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:

成功的JSON

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

不成功響應:

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

問題

如何修改控制器操作以在返回json時考慮兩種情況?

+0

嘿@Antho呃,我看到了你刪除的最新問題。我正要說,有一種更好的方式來創建JSON響應。如果你想我可以在這裏發佈它作爲答案? – dmahapatro

回答

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:[] ] ]