Question

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.

Was it helpful?

Solution 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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top