Grails:在JSON解组中将int转换为枚举

时间:2014-09-26 08:21:14

标签: json grails groovy enums

我使用HttpBuilder来调用REST服务。我需要将JSON响应转换为POGO。

这是一个简化的REST调用:

def http = new HTTPBuilder('http://www.example.com/api')
http.request(Method.POST, ContentType.JSON) {
    /* ... */
    response.success { resp, json ->
        MyPogo pogo = (MyPogo) json
    }
}

它通常有效。

但现在我有这样的JSON:

{ persons: [{ name:"Jhon", gender:0 }, { name:"Mary", gender:1 }] }

而MyPogo有一个Gendern枚举,就像这样:

class MyPogo implements Serializable {
    String name
    Gender gender
}

enum Gender {
    MALE(0),
    FEMALE(1)

    private final int key

    Gender(int key) { this.key = key }
}

使用此POGO,HttpBuilder抛出GrailsCastException(无法将Integer转换为Gender)。

我知道如何将int转换为枚举以及如何注册自定义JSON编组器,但是如何仅为gender enum注册自定义unmarshaller?

编辑:枚举构造函数中的类型定义。

1 个答案:

答案 0 :(得分:0)

尝试在构造函数中添加类型定义:

enum Gender {
    MALE(0),
    FEMALE(1)

    private final int key

    Gender(int key) { 
        this.key = key 
    }
}