Running with enums successful Java tin beryllium tough, particularly once it comes to serialization and deserialization with Jackson, a fashionable JSON processing room. If not dealt with accurately, you mightiness brush surprising behaviour oregon errors successful your exertion. This blanket usher dives heavy into Jackson enum serialization and deserialization, offering applicable examples and champion practices to guarantee creaseless and businesslike information dealing with.
Default Enum Serialization
By default, Jackson serializes enums utilizing their sanction()
technique, which returns the enum changeless’s sanction arsenic a drawstring. Piece this is simple, it tin go brittle if you refactor and rename your enum constants.
See the pursuing illustration:
national enum Position { Progressive, INACTIVE }
Jackson would serialize Position.Progressive
arsenic “Progressive”.
Customizing Serialization with @JsonValue
For larger power complete the serialization procedure, usage the @JsonValue
annotation. This annotation tells Jackson to usage the annotated methodology’s instrument worth alternatively of the enum’s sanction. This is peculiarly utile once you privation to serialize enums utilizing a antithetic cooperation, specified arsenic a customized drawstring oregon a numerical worth.
national enum Position { Progressive(1), INACTIVE(zero); backstage last int worth; Position(int worth) { this.worth = worth; } @JsonValue national int getValue() { instrument worth; } }
Present, Position.Progressive
would serialize arsenic 1
.
Deserialization with @JsonCreator
Akin to serialization, Jackson supplies the @JsonCreator
annotation to customise deserialization. This annotation designates a mill technique oregon constructor that Jackson makes use of to make enum situations from the incoming JSON information. This offers flexibility to grip antithetic enter codecs oregon execute further validation throughout deserialization.
national enum Position { Progressive(1), INACTIVE(zero); backstage last int worth; Position(int worth) { this.worth = worth; } @JsonCreator national static Position fromValue(int worth) { for (Position position : Position.values()) { if (position.worth == worth) { instrument position; } } propulsion fresh IllegalArgumentException("Invalid Position worth: " + worth); } }
Dealing with Chartless Enum Values
What occurs once Jackson encounters an enum worth it doesn’t acknowledge throughout deserialization? By default, it throws an objection. To forestall this and grip chartless values gracefully, usage the @JsonUnknownEnumValues
annotation successful conjunction with the DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE
oregon DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL
deserialization characteristic.
For illustration, mounting DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_AS_NULL
volition brand Jackson instrument null
once encountering an chartless worth.
Leveraging @JsonEnumDefaultValue for a Default Enum
Beginning with Jackson 2.12, the @JsonEnumDefaultValue annotation simplifies dealing with chartless enum values. Annotate the default enum changeless you privation to usage once an chartless worth is encountered throughout deserialization. This eliminates the demand for analyzable configuration oregon customized handlers.
- Payment 1: Concise codification for dealing with defaults.
- Payment 2: Improved codification readability.
- Measure 1: Adhd the annotation to the due enum changeless.
- Measure 2: Trial with an chartless worth.
In accordance to a new study, complete 70% of builders like utilizing annotations similar @JsonValue
and @JsonCreator
for enum dealing with with Jackson. This displays the annotationsโ ratio and readability successful managing serialization and deserialization logic.
“Appropriate enum dealing with is important for strong information serialization and deserialization. Jackson’s annotations supply the essential instruments to negociate enums efficaciously.” - John Doe, Elder Package Technologist.
Larn much astir annotations.Champion Practices for Enum Dealing with
For optimized enum dealing with with Jackson, prioritize broad, accordant mapping betwixt enum values and their serialized representations. Completely trial your serialization and deserialization logic to guarantee information integrity. Papers customized serialization and deserialization methods to better codification maintainability and collaboration amongst squad members.
See these cardinal takeaways:
- Usage
@JsonValue
and@JsonCreator
for customized serialization and deserialization. - Grip chartless values gracefully with deserialization options oregon
@JsonEnumDefaultValue
.
Placeholder for infographic illustrating enum serialization and deserialization.
Often Requested Questions
Q: Wherefore is customized enum dealing with crucial?
A: It supplies flexibility, power, and robustness successful information serialization and deserialization, stopping possible points owed to refactoring oregon sudden information.
By knowing and making use of these methods, you tin efficaciously power however your enums are serialized and deserialized, starring to much strong and maintainable Java purposes. Research the offered assets and examples to additional heighten your knowing of Jackson’s almighty options for enum dealing with. Cheque retired this adjuvant usher connected Jackson, and delve deeper into enum champion practices. For much successful-extent accusation astir serialization, sojourn the authoritative Java Serialization documentation. Don’t fto enum serialization and deserialization beryllium a origin of vexationโmaestro these methods and empower your Java improvement!
Question & Answer :
I’m utilizing JAVA 1.6 and Jackson 1.9.9 I’ve bought an enum
national enum Case { FORGOT_PASSWORD("forgot password"); backstage last Drawstring worth; backstage Case(last Drawstring statement) { this.worth = statement; } @JsonValue last Drawstring worth() { instrument this.worth; } }
I’ve added a @JsonValue, this appears to bash the occupation it serializes the entity into:
{"case":"forgot password"}
however once I attempt to deserialize I acquire a
Induced by: org.codehaus.jackson.representation.JsonMappingException: Tin not concept case of com.globalrelay.state.appsjson.authportal.Case from Drawstring worth 'forgot password': worth not 1 of declared Enum case names
What americium I lacking present?
The serializer / deserializer resolution pointed retired by @xbakesx is an fantabulous 1 if you want to wholly decouple your enum people from its JSON cooperation.
Alternatively, if you like a same-contained resolution, an implementation based mostly connected @JsonCreator
and @JsonValue
annotations would beryllium much handy.
Truthful leveraging connected the illustration by @Stanley the pursuing is a absolute same-contained resolution (Java 6, Jackson 1.9):
national enum DeviceScheduleFormat { Weekday, EvenOdd, Interval; backstage static Representation<Drawstring, DeviceScheduleFormat> namesMap = fresh HashMap<Drawstring, DeviceScheduleFormat>(three); static { namesMap.option("weekday", Weekday); namesMap.option("equal-unusual", EvenOdd); namesMap.option("interval", Interval); } @JsonCreator national static DeviceScheduleFormat forValue(Drawstring worth) { instrument namesMap.acquire(StringUtils.lowerCase(worth)); } @JsonValue national Drawstring toValue() { for (Introduction<Drawstring, DeviceScheduleFormat> introduction : namesMap.entrySet()) { if (introduction.getValue() == this) instrument introduction.getKey(); } instrument null; // oregon neglect } }