@jsonview of jackson not working with jax-rs

自闭症网瘾萝莉.ら 提交于 2020-01-03 08:56:48

问题


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


回答1:


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

    ...
  }
}


来源:https://stackoverflow.com/questions/26775106/jsonview-of-jackson-not-working-with-jax-rs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!