运行Grails 2.4.2我无法从JSON字符串中获取枚举。我认为声明一个接受值的构造函数可以解决问题,但事实并非如此。我也试过传递JSON的名字:" GENERIC",它也没有绑定。
如果值为STRING,则可以绑定到Enum。但这意味着更改枚举的JSON如何为绑定而默认呈现。例如,这有效:
{"id":null,"templateCode": "GENERIC"}
从JSON获取枚举绑定的正确/最佳方法是什么?
class EmailTemplate {
TemplateCode templateCode
}
public enum TemplateCode {
GENERIC('Generic template'),
CUSTOM('Custom template')
final String value
EmailTemplateCode(String value) {
this.value = value
}
String getKey() {
name()
}
String toString() {
value
}
}
在Bootstrap.groovy
JSON.registerObjectMarshaller(Template) {
def map = [:]
map['templateCode'] = it.templateCode
return map
}
JSON.registerObjectMarshaller(TemplateCode) {
def map = [:]
map['name'] = it.name
map['value'] = it.value
return map
}
正在发送的JSON是
{"id":null,"templateCode":{"key":"GENERIC","value":"Generic template"}}
编辑:简化版
如果我们将基本使用enum,那么:
public enum TemplateCode {
GENERIC,CUSTOM
}
Grails将它呈现为JSON:
templateCode: { enumType: com.EmailTemplateCode, name: GENERIC}
但是,发布相同的JSON字符串会产生错误而不会绑定到枚举。如上所述,唯一的方法是将templatecode作为字符串发送:
templateCode: GENERIC
答案 0 :(得分:1)
嗯,这会做你想要的,但可能有一种更好的方式让所有枚举以这种方式呈现。在引导程序中,使用:
JSON.registerObjectMarshaller(TemplateCode) {
return it.toString()
}
这将正确呈现EmailTemplate,如:
{"templateCode":"CUSTOM"}