我正在阅读Moxy ignore invalid fields in json的答案,并且该方法与我要尝试执行的操作匹配,因此我决定尝试一下。

@Provider
public class JsonFeature implements Feature {
    @Override
    public boolean configure(final FeatureContext context) {
        final String disableMoxy = CommonProperties.MOXY_JSON_FEATURE_DISABLE +
                '.' +
                context.getConfiguration().getRuntimeType().name().toLowerCase();
        context.property(disableMoxy, true);
        return true;
    }
}

我创建了一个非常简单的自定义提供程序;
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class JsonProvider extends MOXyJsonProvider {
    @Override
    protected void preWriteTo(Object object, Class<?> type, Type genericType,
                              Annotation[] annotations, MediaType mediaType,
                              MultivaluedMap<String, Object> httpHeaders, Marshaller marshaller)
            throws JAXBException {
        System.out.println("test");
    }

    @Override
    protected void preReadFrom(Class<Object> type, Type genericType, Annotation[] annotations,
                               MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
                               Unmarshaller unmarshaller)
            throws JAXBException {
        System.out.println("test");
    }
}

我都注册了;
register(JsonFeature.class);
register(JsonProvider.class);

然后我用一个简单的GET请求试了一下。
@GET
@Path("test")
public String getTest() {
    return new TestObject();
}

我相信这应该可行,但是preWriteTo或preReadFrom都不会被调用。我还缺少其他步骤吗?我该如何射击?

最佳答案

弄清楚了-对于任何偶然发现它的人。

@Provider
public class JsonFeature implements Feature {
    @Override
    public boolean configure(final FeatureContext context) {
        context.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE_SERVER, true);
        return true;
    }
}
然后像这样扩展可配置的MoxyJsonProvider;
@Provider
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public class JsonProvider extends ConfigurableMoxyJsonProvider {
    @Override
    protected void preWriteTo(Object object, Class<?> type, Type genericType,
                              Annotation[] annotations, MediaType mediaType,
                              MultivaluedMap<String, Object> httpHeaders, Marshaller marshaller)
            throws JAXBException {
        System.out.println("test");
    }

    @Override
    protected void preReadFrom(Class<Object> type, Type genericType, Annotation[] annotations,
                               MediaType mediaType, MultivaluedMap<String, String> httpHeaders,
                               Unmarshaller unmarshaller)
            throws JAXBException {
        System.out.println("test");
    }
}

09-29 21:25