Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@jsonview of jackson not working with jax-rs

I have written 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 am expecting output as

{a: vlaue}

but i am recieving

{a: value, b: value}

Please let me know what is wrong in this code.

i am using jackson version 2.4.2

like image 489
Jayendra Gothi Avatar asked Nov 06 '14 08:11

Jayendra Gothi


1 Answers

The reason for this behavior is the MapperFeature DEFAULT_VIEW_INCLUSION.

From the Javadoc:

Default value is enabled, meaning that non-annotated properties are included in all views if there is no JsonView annotation

In Jersey you can disable this feature via the JacksonJaxbJsonProvider. This should work in a similar way for other JAX-RS frameworks.

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

    ...
  }
}
like image 172
gillesB Avatar answered Oct 20 '22 23:10

gillesB