@jsonview Jackson does not work with jax-rs

I wrote the following code:

class A{
    public static class Public { }
}

// Entity class
public class B{
    @JsonView({A.Public.class}) 
    int a;
    int b;    
}

public class C{
    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @JsonView({A.Public.class}) 
    public Bed getData(){
        // return object of B
    }
}

I expect the conclusion to be

{a: vlaue}

but i get

{a: value, b: value}

Please let me know what is wrong with this code.

I am using Jackson version 2.4.2

+4
source share
1 answer

The reason for this behavior is MapperFeature DEFAULT_VIEW_INCLUSION.

From Javadoc:

The default value is enabled, which means that non-annotated properties are included in all views if there is no JsonView annotation

In Jersey, you can disable this feature with JacksonJaxbJsonProvider. This should work similarly for other JAX-RS infrastructures.

@ApplicationPath("/api")
public class MyApplication extends ResourceConfig {
  public MyApplication() {
    ...

    JacksonJaxbJsonProvider provider = new JacksonJaxbJsonProvider();
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);    
    provider.setMapper(objectMapper);

    register(provider);

    ...
  }
}
+4
source

All Articles