Jax rs enum反序列化不区分大小写

时间:2018-04-16 12:34:07

标签: java jackson jax-rs

我有一个使用json请求的休息Web服务:

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Request {
    @XmlElement
    private List<Update> update;
}

请求是更新列表:

@XmlAccessorType(XmlAccessType.FIELD)
public class Update implements Serializable {
    private static final long serialVersionUID = 1L;

    @XmlElement(name = "ID")
    private Integer id;

    @XmlElement(name = "Status")
    private Status status;
}

并且Update类有一个枚举字段:

@XmlEnum
public enum Status  {
    @XmlEnumValue("active")
    ACTIVE("active"), 
    @XmlEnumValue("cancelled")
    CANCELLED("cancelled"); 
}

状态是一个枚举:

@Provider
public class IgnoreCaseDeserializer extends StdDeserializer<Status>{

    private static final long serialVersionUID = 1L;

    public IgnoreCaseDeserializer() {
        this(null);
    }

    protected IgnoreCaseDeserializer(Class<?> vc) {
        super(vc);
    }

    @Override
    public Status deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        return Status.fromString(jp.getValueAsString().toLowerCase());
    }
}

我希望将字符串“active”,“Active”,“ACTIVE”,...反序列化为enum ACTIVE,但所有尝试都失败:Update java对象中的status字段为null(从String转换)枚举失败,使用Active或ACTIVE输入字符串)

我尝试创建自定义反序列化程序但不确定我做得好:

@JsonDeserialize(using=IgnoreCaseDeserializer.class)
@XmlEnum
public enum HopperStatus  

我添加了@JsonDeserialize注释:

{{1}}

我做错了什么?

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

先建议。如果您将XML元素和属性声明为大写,则最好将所有元素和属性声明为大写。所以

@XmlRootElement(name = "Request") public class Request

@XmlAccessorType(XmlAccessType.FIELD) @XmlRootElement(name = "Update") public class Update implements Serializable {

@XmlElement(name = "Updates") private List<Update> update;

对于基本类型和字符串,我们通常将它们公布为@XMLAttribute,对于类和枚举,我们将它们公布为@XMLElement

并且您应该附加请求XML内容,这很重要。我根据你的定义来创造它。

<Request>
  <Updates>
    <Update>
      <ID>1</ID>
      <Status>active</Status>
    </Update>
  </Updates>
</Request>

对于activeACTIVEActive请求内容转换,建议您使用XMLAdapter

public class StatusAdapter extends XMLAdapter<String, Status> {
    @Override
    public Status unmarshal(String status) throws Exception {

        return Status.fromValue(status.toLowerCase()); /* ensure status is not 
           blank, or you should check null before toLowerCase(). Usually, `required` is
     set in XML annotations, eg @XMLAttribute(name = "name", required = true) */
    }

    @Override
    public String marshal(Status status) throws Exception {

        return status.value();
    }
}

并将适配器添加到您使用的状态。

@XmlElement(name = "Status", required = true)
@XMLJavaTypeAdapter(StatusAdapter.class)
private Status status;