Search code examples
javajacksonjackson-databind

How to deserialize JSON string to enum


I have the JSON looks like the following:

{
  "name": "john",
  "options": {
    "test": 1,
    "operation": "op1",     // I need to deserialize this option to enum.
    ...
    // any number of options
  }
}

and I have the class looks like the following:

public class Info {
    public String name;
    @JsonTypeInfo(use = JsonTypeInfo.Id.NONE)
    public Map<String, Object> options;
}

public enum OperationEnum {OP1, OP2, OP3}

How can I deserialize to options map operation like enum and test to Integer


Solution

  • You should be able to use @JsonAnySetter to help you out here:

    public class Info {
        public static class Options {
          public int test;
          public OperationEnum operation;
        }
    
        public String name;
        public Options options;
        private final Map<String, Object> properties = new HashMap<>();
    
        @JsonAnySetter
        public void add(String key, String value) {
            properties.put(key, value);
        }
    
    }
    
    public enum OperationEnum {OP1, OP2, OP3}
    

    There's a good write-up here: https://www.concretepage.com/jackson-api/jackson-jsonanygetter-and-jsonanysetter-example