I am curious to know which JSON marshalling/unmarshalling framework is used by Glassfish/Payara is case of JAX-RS and how I can add custom JSON mapper class into it.
I would like to write a custom serializer for my Enum
class. I use provided
scope in my pom.xml for jaxrs javaee-api
7.0 so default Glassfish libraries are used.
I tried to use @JsonValue
and wrote a class which implements javax.ws.rs.ext.MessageBodyWriter
and JsonSerializer<T>
as well. Do not work either as I expect.
This is my enum class:
public enum ErrorCode {
MY_ERROR(123456);
private int value;
ErrorCode(final int value) {
this.value = value;
}
@JsonValue
public int getValue() {
return value;
}
}
The class which uses enum:
public class ErrorInfo {
private ErrorCode errorCode;
public String toJson() {
try {
return new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(this);
} catch (JsonProcessingException e) {
// TODO: do something here...
}
}
}
And the JAX-RS class where I would like to send back the ErrorInfo
instance as a JSON:
@Provider
public class MyExceptionMapper implements ExceptionMapper<Throwable> {
@Override
public Response toResponse(Throwable throwable) {
...
return Response
.status(errorInfo.getHttpStatus())
.type(ExtendedMediaType.APPLICATION_JSON_UTF8)
.entity(errorInfo)
.build();
}
}
If I use the code above then the errorCode
value is "MY_ERROR" string instead of the int 123456 value.
If I use my extra errorInfo.toJson()
method then @JsonValue annotation does the magic but I would like to avoid writing extra code to handle enum serialization issue.
What is the proper way to configure / add extra enum mapper class to the default JAX-RS JSON library in Glassfish/Payara?
By default, Payara Server uses MOXy to map to/from JSON. You can use an alternative like Jackson, if you add Jackson to your app and add JacksonFeature
into JAX-RS classes: Force Glassfish4 to use Jackson instead of Moxy
In the upcoming Payara 5, which will support Java EE 8, JSON marshalling will be handled in a standard way prescribed by the JSON-Binding