Reputation: 314
I have an Enum which goes something like this:
public enum Level {
HIGH ("hi"),
MEDIUM("med"),
LOW ("lo")
;
private final String levelCode;
private Level(String levelCode) {
this.levelCode = levelCode;
}
}
This enum is element in another request class like :
public class RequestPOJO{
Level level;
int somefield1; //other instance varilables
//...... other instance varilables
}
I want to map a string field (with name levelCode) in JSON request to this enum. I'm using Jackson for serialisation. Is there any way to map this string field in request directly to this enum.
Upvotes: 0
Views: 2023
Reputation: 46
You can use @JsonValue
annotation for a new method inside the enum
. That method should return the String
which is nothing but levelCode
in your example. If done so, this solves your problem for both serialization and deserialization.
Just to keep you informed, this would not work the same way if the enum
has an int
field due to a bug with Jackson. In such case you need to follow a different approach using @JsonCreator
.
You can refer to my blog for implementation examples.
Upvotes: 2