rak*_*ell 37 java json jackson
Jackson 1.6.2 REST Web服务/ Apache Wink
如何对枚举字段进行注释以便杰克逊对其进行反序列化?
public enum BooleanField
{
BOOLEAN_TRUE { public String value() { return "1";} },
BOOLEAN_FALSE { public String value() { return "0";} },
Run Code Online (Sandbox Code Playgroud)
BooleanField locked;
public BooleanField getLocked() {return locked;}
Run Code Online (Sandbox Code Playgroud)
杰克逊文档声明它可以通过@JsonValue/ 执行此操作@JsonCreator但不提供任何示例(如何有用!).我敢肯定他们只是不想让太多人使用他们的框架,所以他们保守这个秘密.
有人愿意溢出(java)bean吗?
Sta*_*Man 46
如果您使用的是Jackson 1.9,序列化将通过以下方式完成:
public enum BooleanField {
BOOLEAN_TRUE("1")
;
// either add @JsonValue here (if you don't need getter)
private final String value;
private BooleanField(String value) { this.value = value; }
// or here
@JsonValue public String value() { return value; }
Run Code Online (Sandbox Code Playgroud)
所以改变你需要的是向Enum类型本身添加方法,所以所有值都有它.不确定它是否适用于子类型.
因为@JsonCreator,有一个静态工厂方法会这样做; 所以添加如下内容:
@JsonCreator
public static BooleanField forValue(String v) { ... }
Run Code Online (Sandbox Code Playgroud)
Jackson 2.0实际上将支持仅@JsonValue用于两者,包括反序列化.
sof*_*arn 35
随着杰克逊2.7.2或更新
public enum BooleanField
{
@JsonProperty("1")
BOOLEAN_TRUE,
@JsonProperty("0")
BOOLEAN_FALSE
}
Run Code Online (Sandbox Code Playgroud)
luc*_*ler 15
不要注释它们,只需配置您的ObjectMapper实例:
private ObjectMapper createObjectMapper() {
final ObjectMapper mapper = new ObjectMapper();
// enable toString method of enums to return the value to be mapped
mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
return mapper;
}
Run Code Online (Sandbox Code Playgroud)
并在您的枚举中重写toString()方法:
public enum SectionType {
START("start"),
MORE("more");
// the value which is used for matching
// the json node value with this enum
private final String value;
SectionType(final String type) {
value = type;
}
@Override
public String toString() {
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
您不需要任何注释或自定义反序列化器.
| 归档时间: |
|
| 查看次数: |
69291 次 |
| 最近记录: |