使用Jackson反序列化EnumMap时@JsonAnySetter报错的解决咨询
Got it, let's break down why you're seeing this error and walk through the fix.
Why the Error Occurs
Jackson's @JsonAnySetter annotation has a hard requirement: the first parameter of the annotated method must be either String or Object. This is because Jackson parses JSON object keys as strings by default, and it can't automatically convert those strings to your custom Enum type directly in an any-setter method. That's why switching to a HashMap<String, String> works—it aligns with Jackson's expected parameter type for the key.
Solution: Add a Middleman Any-Setter Method
The most straightforward fix is to create a temporary @JsonAnySetter method that accepts a String key, converts it to your MyEnum, then passes it to your actual EnumMap-handling logic. Here's the code:
// Your EnumMap storage private Map<MyEnum, String> mymap = new EnumMap<>(MyEnum.class); // Core method to populate the EnumMap (no annotation here) private void addProperty(MyEnum key, Object value) { // Adjust value conversion based on your actual data types mymap.put(key, value.toString()); } // Jackson calls this for all unknown JSON properties @JsonAnySetter public void addStringProperty(String key, Object value) { // Convert string key to your Enum MyEnum enumKey = MyEnum.valueOf(key); addProperty(enumKey, value); }
Handling Custom Enum-to-String Mappings
If your JSON keys don't exactly match the name() of your Enum constants (e.g., JSON uses lowercase or hyphenated keys), use Jackson annotations to define the mapping:
Option 1: @JsonProperty on Enum Constants
Directly map JSON keys to Enum values:
public enum MyEnum { @JsonProperty("first_property") FIRST_PROPERTY, @JsonProperty("second_property") SECOND_PROPERTY; }
Option 2: @JsonCreator for Custom Conversion
For more control (like case-insensitive matching), add a static factory method:
public enum MyEnum { FIRST_PROPERTY, SECOND_PROPERTY; @JsonCreator public static MyEnum fromString(String key) { // Example: Convert input to uppercase and replace hyphens with underscores return MyEnum.valueOf(key.toUpperCase().replace("-", "_")); } }
Handling Invalid Enum Keys
To avoid crashes when JSON contains unrecognized keys, add error handling to the middleman method:
@JsonAnySetter public void addStringProperty(String key, Object value) { try { MyEnum enumKey = MyEnum.valueOf(key); addProperty(enumKey, value); } catch (IllegalArgumentException e) { // Choose your handling strategy: log, ignore, or throw a custom exception System.err.println("Skipping invalid Enum key: " + key); } }
内容的提问来源于stack exchange,提问作者Vivek

