Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to manually map Enum fields in JAX-RS

How can I map a simple JSON object {"status" : "successful"} automaticly map to my Java Enum within JAX-RS?

public enum Status {
    SUCESSFUL ("successful"), 
    ERROR ("error");

    private String status;

    private Status(String status) {
        this.status = status;
    }
}

If you need further details feel free to ask :)

like image 535
Tobias Sarnow Avatar asked Sep 04 '12 09:09

Tobias Sarnow


People also ask

Can enum be map key?

You can use Enum as well as any other Object as key. 2. Performance : EnumMap is a specialized Map implementation for use with enum type keys. EnumMaps are represented internally as arrays.

Can enums map?

A specialized Map implementation for use with enum type keys. All of the keys in an enum map must come from a single enum type that is specified, explicitly or implicitly, when the map is created. Enum maps are represented internally as arrays. This representation is extremely compact and efficient.

How does Jackson deserialize enum?

By default, Jackson will use the Enum name to deserialize from JSON. If we want Jackson to case-insensitively deserialize from JSON by the Enum name, we need to customize the ObjectMapper to enable the ACCEPT_CASE_INSENSITIVE_ENUMS feature.


2 Answers

The following JAXB annotations should do it. (I tested using Jettison but I've not tried other providers):

@XmlType(name = "status")
@XmlEnum
public enum Status {
    @XmlEnumValue(value = "successful")
    SUCESSFUL, 
    @XmlEnumValue(value = "error")
    ERROR;
}
like image 140
David J. Liszewski Avatar answered Sep 20 '22 15:09

David J. Liszewski


This might help you

@Entity
public class Process {

  private State state;

  public enum State {
    RUNNING("running"), STOPPED("stopped"), PAUSED("paused");

    private String value;

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

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

    @JsonCreator
    public static State create(String val) {
      State[] states = State.values();
      for (State state : states) {
        if (state.getValue().equalsIgnoreCase(val)) {
          return state;
        }
      }
      return STOPPED;
    }
  }
}
like image 37
peer Avatar answered Sep 22 '22 15:09

peer