我正在使用JAVA 1.6和Jackson 1.9.9我有一个枚举
public enum Event {
FORGOT_PASSWORD("forgot password");
private final String value;
private Event(final String description) {
this.value = description;
}
@JsonValue
final String value() {
return this.value;
}
}
我添加了一个@JsonValue,这似乎完成了将对象序列化为:
{"event":"forgot password"}
但是当我尝试反序列化时,我得到了一个
Caused by: org.codehaus.jackson.map.JsonMappingException: Can not construct instance of com.globalrelay.gas.appsjson.authportal.Event from String value 'forgot password': value not one of declared Enum instance names
我在这里错过了什么?
@xbakesx指出的串行器/解串器解决方案是一个很好的解决方案,如果你想完全将你的枚举类与其JSON表示分离。
或者,如果您更喜欢自包含的解决方案,那么基于@JsonCreator
和@JsonValue
注释的实现将更加方便。
因此,利用@Stanley的示例,以下是一个完整的自包含解决方案(Java 6,Jackson 1.9):
public enum DeviceScheduleFormat {
Weekday,
EvenOdd,
Interval;
private static Map<String, DeviceScheduleFormat> namesMap = new HashMap<String, DeviceScheduleFormat>(3);
static {
namesMap.put("weekday", Weekday);
namesMap.put("even-odd", EvenOdd);
namesMap.put("interval", Interval);
}
@JsonCreator
public static DeviceScheduleFormat forValue(String value) {
return namesMap.get(StringUtils.lowerCase(value));
}
@JsonValue
public String toValue() {
for (Entry<String, DeviceScheduleFormat> entry : namesMap.entrySet()) {
if (entry.getValue() == this)
return entry.getKey();
}
return null; // or fail
}
}
试试这个。
public enum Event { FORGOT_PASSWORD("forgot password"); private final String value; private Event(final String description) { this.value = description; } private Event() { this.value = this.name(); } @JsonValue final String value() { return this.value; } }
除了使用@JsonSerialize @JsonDeserialize之外,您还可以在对象映射器中使用SerializationFeature和DeserializationFeature(jackson binding)。
例如DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE,如果枚举类中未定义提供的枚举类型,则提供默认枚举类型。
我发现最简单的方法是使用@ JsonFormat.Shape.OBJECT注释作为枚举。
@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum MyEnum{
....
}
请注意,截至2015年6月的this commit(杰克逊2.6.2及更高版本),您现在可以简单地写道:
public enum Event {
@JsonProperty("forgot password")
FORGOT_PASSWORD;
}
您应该创建一个静态工厂方法,该方法采用单个参数并使用@JsonCreator
进行注释(自Jackson 1.2起可用)
@JsonCreator
public static Event forValue(String value) { ... }
阅读更多关于JsonCreator注释here的信息。
实际答案:
枚举的默认反序列化器使用.name()
反序列化,因此它不使用@JsonValue
。所以@OldCurmudgeon指出,你需要传入{"event": "FORGOT_PASSWORD"}
以匹配.name()
值。
另一个选项(假设您希望写入和读取json值相同)...
更多信息:
还有另一种管理Jackson的序列化和反序列化过程的方法。您可以指定这些注释以使用您自己的自定义序列化程序和反序列化程序:
@JsonSerialize(using = MySerializer.class)
@JsonDeserialize(using = MyDeserializer.class)
public final class MyClass {
...
}
然后你必须写MySerializer
和MyDeserializer
,如下所示:
MySerializer
public final class MySerializer extends JsonSerializer<MyClass>
{
@Override
public void serialize(final MyClass yourClassHere, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
// here you'd write data to the stream with gen.write...() methods
}
}
MyDeserializer
public final class MyDeserializer extends org.codehaus.jackson.map.JsonDeserializer<MyClass>
{
@Override
public MyClass deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
// then you'd do something like parser.getInt() or whatever to pull data off the parser
return null;
}
}
最后一点,特别是对于使用JsonEnum
方法序列化的枚举getYourValue()
,你的序列化器和反序列化器可能如下所示:
public void serialize(final JsonEnum enumValue, final JsonGenerator gen, final SerializerProvider serializer) throws IOException, JsonProcessingException
{
gen.writeString(enumValue.getYourValue());
}
public JsonEnum deserialize(final JsonParser parser, final DeserializationContext context) throws IOException, JsonProcessingException
{
final String jsonValue = parser.getText();
for (final JsonEnum enumValue : JsonEnum.values())
{
if (enumValue.getYourValue().equals(jsonValue))
{
return enumValue;
}
}
return null;
}
我找到了一个非常简洁的解决方案,当你不能像我的情况那样修改枚举类时特别有用。然后,您应该提供自定义的ObjectMapper,并启用某个功能。自Jackson 1.6以来,这些功能可用。因此,您只需要在枚举中编写toString()
方法。
public class CustomObjectMapper extends ObjectMapper {
@PostConstruct
public void customConfiguration() {
// Uses Enum.toString() for serialization of an Enum
this.enable(WRITE_ENUMS_USING_TO_STRING);
// Uses Enum.toString() for deserialization of an Enum
this.enable(READ_ENUMS_USING_TO_STRING);
}
}
有更多与枚举相关的功能,请参见此处:
https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features
您可以自定义任何属性的反序列化。
使用annotationJsonDeserialize(import com.fasterxml.jackson.databind.annotation.JsonDeserialize
)为要处理的属性声明反序列化类。如果这是一个枚举:
@JsonDeserialize(using = MyEnumDeserialize.class)
private MyEnum myEnum;
这样,您的类将用于反序列化属性。这是一个完整的例子:
public class MyEnumDeserialize extends JsonDeserializer<MyEnum> {
@Override
public MyEnum deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
JsonNode node = jsonParser.getCodec().readTree(jsonParser);
MyEnum type = null;
try{
if(node.get("attr") != null){
type = MyEnum.get(Long.parseLong(node.get("attr").asText()));
if (type != null) {
return type;
}
}
}catch(Exception e){
type = null;
}
return type;
}
}
这是另一个使用字符串值而不是映射的示例。
public enum Operator {
EQUAL(new String[]{"=","==","==="}),
NOT_EQUAL(new String[]{"!=","<>"}),
LESS_THAN(new String[]{"<"}),
LESS_THAN_EQUAL(new String[]{"<="}),
GREATER_THAN(new String[]{">"}),
GREATER_THAN_EQUAL(new String[]{">="}),
EXISTS(new String[]{"not null", "exists"}),
NOT_EXISTS(new String[]{"is null", "not exists"}),
MATCH(new String[]{"match"});
private String[] value;
Operator(String[] value) {
this.value = value;
}
@JsonValue
public String toStringOperator(){
return value[0];
}
@JsonCreator
public static Operator fromStringOperator(String stringOperator) {
if(stringOperator != null) {
for(Operator operator : Operator.values()) {
for(String operatorString : operator.value) {
if (stringOperator.equalsIgnoreCase(operatorString)) {
return operator;
}
}
}
}
return null;
}
}
您可以采用各种方法来完成对枚举的JSON对象的反序列化。我最喜欢的风格是做一个内部课:
import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonProperty;
import org.hibernate.validator.constraints.NotEmpty;
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
import static com.fasterxml.jackson.annotation.JsonFormat.Shape.OBJECT;
@JsonFormat(shape = OBJECT)
public enum FinancialAccountSubAccountType {
MAIN("Main"),
MAIN_DISCOUNT("Main Discount");
private final static Map<String, FinancialAccountSubAccountType> ENUM_NAME_MAP;
static {
ENUM_NAME_MAP = Arrays.stream(FinancialAccountSubAccountType.values())
.collect(Collectors.toMap(
Enum::name,
Function.identity()));
}
private final String displayName;
FinancialAccountSubAccountType(String displayName) {
this.displayName = displayName;
}
@JsonCreator
public static FinancialAccountSubAccountType fromJson(Request request) {
return ENUM_NAME_MAP.get(request.getCode());
}
@JsonProperty("name")
public String getDisplayName() {
return displayName;
}
private static class Request {
@NotEmpty(message = "Financial account sub-account type code is required")
private final String code;
private final String displayName;
@JsonCreator
private Request(@JsonProperty("code") String code,
@JsonProperty("name") String displayName) {
this.code = code;
this.displayName = displayName;
}
public String getCode() {
return code;
}
@JsonProperty("name")
public String getDisplayName() {
return displayName;
}
}
}
在枚举的上下文中,现在使用@JsonValue
(自2.0开始)用于序列化和反序列化。
根据jackson-annotations javadoc for @JsonValue
:
注意:当用于Java枚举时,另外一个特性是注释方法返回的值也被认为是反序列化的值,而不仅仅是要序列化的JSON字符串。这是可能的,因为Enum值的集合是常量并且可以定义映射,但是对于POJO类型通常不能完成;因此,这不用于POJO反序列化。
因此,如上所述,使用jackson 2.0+对Event
枚举进行注释(对于序列化和反序列化)。