在 Glassfish/Payara 上使用 JAX-RS 进行自定义 Json 编组

Custom Json marshalling with JAX-RS on Glassfish/Payara

我很想知道 Glassfish/Payara 使用哪个 json marshalling/unmarshalling 框架是 JAX-RS 的情况,以及如何添加自定义 json 映射器 class进入其中。

我想为我的 Enum class 编写自定义序列化程序。我在我的 pom.xml 中为 jaxrs javaee-api 7.0 使用 provided 范围,因此使用默认的 Glassfish 库。

我尝试使用 @JsonValue 并编写了一个 class 来实现 javax.ws.rs.ext.MessageBodyWriterJsonSerializer<T>。也不如我所愿

这是我的枚举 class:

public enum ErrorCode {
    MY_ERROR(123456);

    private int value;

    ErrorCode(final int value) {
        this.value = value;
    }

    @JsonValue
    public int  getValue() {
        return value;
    }
}

使用枚举的class:

public class ErrorInfo {
    private ErrorCode errorCode;

    public String toJson() {
        try {
            return new ObjectMapper().writer().withDefaultPrettyPrinter().writeValueAsString(this);
        } catch (JsonProcessingException e) {
            // TODO: do something here...
        }
    }
}

还有 JAX-RS class,我想在其中将 ErrorInfo 实例作为 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();
    }
}

如果我使用上面的代码,那么 errorCode 值是 "MY_ERROR" 字符串而不是 int 123456 值。

如果我使用额外的 errorInfo.toJson() 方法,那么 @JsonValue 注释会产生魔力,但我想避免编写额外的代码来处理枚举序列化问题。

将额外的枚举映射器 class 配置/添加到 Glassfish/Payara 中的默认 JAX-RS json 库的正确方法是什么?

默认情况下,Payara 服务器使用 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

在即将支持 Java EE 8 的 Payara 5 中,JSON 编组将按照 JSON-Binding

规定的标准方式进行处理