15

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 :)

Tobias Sarnow
  • 1,076
  • 2
  • 12
  • 40

2 Answers2

15

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;
}
David J. Liszewski
  • 10,959
  • 6
  • 44
  • 57
  • Thanks for you answer. I'm using standard JAX-RS features and the application server decides which implementation will be uses. In my case it's JBoss 7.1 and it uses jackson automatically (i guess). Do you know if there is a way to force jBoss using another provider? Or enable jBoss to use `XmlEnum` and `XmlEnumValue`? – Tobias Sarnow Sep 06 '12 at 06:52
  • It is possible that `Jackson` will behave similar to Jettison with respect to the JAXB annotations – I simply didn't have the time to try it. BTW, if it wasn't clear, the annotations above are standard JAXB which JAX-RS implementations should follow. – David J. Liszewski Sep 06 '12 at 15:56
7

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;
    }
  }
}
peer
  • 165
  • 1
  • 7