Search code examples
javajsonenumspersistence

Persistance annotation for enum values in a list


To convert Java Objects to and from JSON, we are using annotation on enum types. Suppose we have this type:

public enum MyEnum {
  HELLO,
  WORLD
}

Then we are using it in this manner:

import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import java.io.Serializable;
import java.util.List;

public class SerializableObject implements Serializable{
  @Enumerated(EnumType.STRING)
  private MyEnum singleValue;
  // What annotation do I put here?
  private List<MyEnum> multiValue;
}

My question is: What annotation goes onto the list multiValue so that the contained enum values are properly serialized?


Solution

  • You can use EnumType.ORDINAL

    import java.io.Serializable;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import javax.persistence.EnumType;
    import javax.persistence.Enumerated;
    
    enum MyEnum {
        HELLO, WORLD
    }
    
    
    public class SerializableObject implements Serializable {
        @Enumerated(EnumType.STRING)
        private MyEnum       singleValue;
        // What annotation do I put here?
        @Enumerated(EnumType.ORDINAL)
        private List<MyEnum> multiValue;
    
    
        public void show() {
    
            multiValue = new ArrayList<>(Arrays.asList(MyEnum.values()));
            multiValue.stream().forEach(
                    element -> System.out.println(element.ordinal() + " " + element.toString()));
        }
    
    
        public static void main(String[] args) {
    
            new SerializableObject().show();
        }
    }