泽西2中的自定义MOXyJsonProvider无法正常工作?

时间:2015-03-16 15:47:34

标签: java json jersey jersey-2.0 moxy

我正在阅读Moxy ignore invalid fields in json的答案,并且该方法与我尝试做的事情相符,所以我决定试一试..我创建了一个功能来禁用默认的ConfigurableMoxyJsonProvider; < / p>

@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都没有被调用过..还有另外一步我错过了吗?我怎样才能解雇这些?

1 个答案:

答案 0 :(得分:3)

想出来 - 对于那些偶然发现它的人来说。关闭默认设置的正确方法是;

@Provider
public class JsonFeature implements Feature {
    @Override
    public boolean configure(final FeatureContext context) {
        context.property(CommonProperties.MOXY_JSON_FEATURE_DISABLE_SERVER, true);
        return true;
    }
}

然后像这样扩展ConfigurableMoxyJsonProvider;

@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");
    }
}