inanutshellus
inanutshellus

Reputation: 10001

How to deserialize a complex custom enum in Jackson without hand-rolling a JsonDeserializer?

I have an enum with multiple custom attributes. I'm able to serialize it, and I've created a @JsonCreator method to deserialize it, but it's not working:

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.JsonNode;

@JsonFormat(shape = JsonFormat.Shape.OBJECT)
public enum SomeEnum {
    SOME_VALUE("Blah blah blah", "Example description");

    private final String displayName;
    private final String description;

    ScheduleOptimizationRuleCode(String displayName, String description) {
        this.displayName = displayName;
        this.description = description;
    }

    public String getCode() { return this.name(); }

    public String getDisplayName() {
        return displayName;
    }

    public String getDescription() {
        return description;
    }

    @JsonCreator
    public static SomeEnum fromString(@JsonProperty("code") String value) {
         return SomeEnum.valueOf(value);
    }
}

When serializing, I get the following (correct) output:

{
  "code": "SOME_VALUE",
  "displayName": "Blah blah blah", 
  "description": "Example description"
}

When deserializing, my understanding was that Jackson would look in the object representation of my JSON string, dig out the code attribute, and pass in the code as a string to the @JsonCreator annotated method fromString(), but it doesn't work. value is always null.

I've also tried configuring the "mode" on the @JsonCreator annotation (e.g. PROPERTIES, DELEGATING), but it doesn't work. All the examples I've seen only have a single value, so don't have this issue.

I know I can hand-roll a JsonDeserializer and wire it in... and in the Jackson doc, but surely this isn't so complex that I need a hand-made deserializer...

How do I deserialize an enum with multiple attributes?

Upvotes: 0

Views: 1447

Answers (1)

inanutshellus
inanutshellus

Reputation: 10001

Finally found an example of deserializing an enum, though only one of the two examples works. From looking at his enum I saw that he was passing in a JsonNode. Worked like a charm!

@JsonCreator
public static SomeEnum fromString(JsonNode json) {
     return SomeEnum.valueOf(json.get("code").asText());
}

Upvotes: 3

Related Questions