문제

I am currently attempting to unmarshal a JSON object provided via a REST PUT using Glassfish 4 (which uses Jersery 2.0 and EclipseLink 2.5).

The JSON object consists of a several properties including a String value that gets mapped to a Java Enum.

Everything is working as expected apart from when an invalid ENUM value is provided in the payload

The JSON object:

{
  "rating":"INVALID",
  ...
}

Is unmarshalled into:

public RatingInfo {
    @ValidRating
    private Rating rating;
    ...

    public Rating getRating(){...}
    public void setRating(Rating rating){...}
    ...
}

public enum Rating {
    G,
    PG
}

If the value in the JSON payload is not a valid Rating it currently returns null which appears to be a result of JAXB ignoring the conversion error see Handling invalid enum values while doing JAXB Unmarshalling

The problem is I need to distinguish between the case where Rating is actually null (which is valid use case) vs where the Rating value in the JSON is invalid so that I can return a 400 error in the REST response.

What I can not figure out how to do is override the default behavior of ignoring conversion errors when using JAX-RS with MOXy as the default provider.

도움이 되었습니까?

해결책 2

I have worked round the problem for now by changing the Rating Enum variable in RatingInfo to a String:

public RatingInfo {
    @ValidRating
    private String rating;
    ....
}

In the ValidRating bean validator I then validate the String value against the enum to ensure the passed in String is a a valid rating, if this fails the framework throws a ConstraintViolationException that I map to a 400.

This is not ideal as I would prefer to use an Enum in my RatingInfo bean but it does solve the problem for now.

다른 팁

The easiest thing to do would be to create an XmlAdapter and handle the String to enum conversion yourself. Then you can act accordingly when the value is incorrect.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top