-1

Hi is it possible to change name of ENUM in Java? For example, I have enum -

public enum CloudType {
    AZURE, OPENSTACK
}

And a class -

public class Env{
   private CloudType cloudType;
}

And during JACKSON parsing, if I give -

{
  "cloudType":"AZURE"
}

Or

{
  "cloudType":"azure"
}

It will give me an Env object with cloudType=AZURE ?

One thread is there (Jackson databind enum case insensitive), but really we need to do this much? Or

@XmlEnumValue("azure")
    AZURE("azure"),

will be enough?

CR Sardar
  • 921
  • 2
  • 17
  • 32
  • 4
    Why don't you simply try it? – NiVeR Apr 24 '18 at 10:47
  • 1
    That's not changing the name of an enum, is it? It's just assigning a value to an enum variable. – khelwood Apr 24 '18 at 10:48
  • 2
    Possible duplicate of [Jackson databind enum case insensitive](https://stackoverflow.com/questions/24157817/jackson-databind-enum-case-insensitive) – Michael Apr 24 '18 at 10:50
  • tl;dr : `MapperFeature.ACCEPT_CASE_INSENSITIVE_ENUMS` – Michael Apr 24 '18 at 10:51
  • Actually I am doing serialization directly from REST request body which is capable of handling both Json & XML – CR Sardar Apr 24 '18 at 11:10
  • Hi, kindly please clarify the question, you are asking for more different things, or there are just missing some clues? Eg. How to rename during (de)serialization ? Because the correct answer can be like `Right click in your IDE to enum / class name and choose refactor - change name` ... Kindly please follow [mcve] and [How to ask](https://stackoverflow.com/help/how-to-ask) At this point, its unclear what are you asking for. – xxxvodnikxxx Apr 24 '18 at 11:20

1 Answers1

1

You can decouple the Java names of the enum instances from their JSON representations.

You should add a @JsonValue-annotated method to your enum CloudType to tell Jackson which value to use when reading/writing JSON. For that you also need a constructor to initialize this value.

Like this:

public enum CloudType {
    AZURE("azure"),
    OPENSTACK("openstack");

    private final String value;

    private CloudType(String value) {
        this.value = value;
    }

    @JsonValue
    public String getValue() {
        return value;
    }
}

Then Jackson will serialize CloudType.AZURE to "azure",
and deserialize "azure" to CloudType.AZURE.

Thomas Fritsch
  • 9,639
  • 33
  • 37
  • 49