Using @JsonView in Spring MVC 4 + jackson 2.5

702 views Asked by At

I am going to develop a JSON REST service using Spring MVC 4.0.4 , Hibernate 4.3.5 and Jackson 2.5.4. For the controllers i need the @JsonView to filter properties.

I have annotated some of Model's properties with @JsonView(View.Summary.class) and @JsonView(View.Details.class). when i annotate the controllers for filtering their results (with @JsonView(View.Summary.class) ), it returns all of the annotated properties without considering the passed view class ( View.Summary.class ).

View Classes:

public class View {
    public static interface Summary{}
    public static interface Details extends Summary{}
}

Model :

@Entity
@Table(name="image")
public class Image {

    @JsonView(View.Summary.class)
    private int id;
    private String thumbnailURL;

    @JsonView(View.Details.class)
    private String imageURL;
    private Date registrationDate;
    private int price;

    //..... getters and setters
}

Controller:

@JsonView(View.Summary.class)
@RequestMapping(method = RequestMethod.GET, value = "/service/images")
public  List<Image> getAllImages(HttpServletResponse response) {
        List<Image> list;
        // codes for fetching the result 
        return list;
}

Spring Message Converter:

<mvc:message-converters>
         <bean class="org.springframework.http.converter.StringHttpMessageConverter" /> 
         <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
            <property name="objectMapper">
                <bean class="com.digimind.utils.HibernateAwareObjectMapper">
                </bean>
            </property>
        </bean> 
    </mvc:message-converters>

HibenrateAwareObjectMapper:

public class HibernateAwareObjectMapper extends ObjectMapper {

    public HibernateAwareObjectMapper() {

        Hibernate4Module hm = new Hibernate4Module();
        registerModule(hm);
        this.disable(MapperFeature.DEFAULT_VIEW_INCLUSION);
        this.disable(MapperFeature.AUTO_DETECT_GETTERS);

    }
}

Result:

    [
       {
          "id": 3,
          "imageURL": "url3"
       },
       {
          "id": 2,
          "imageURL": "url 2"
       }
   ]

Expected Result:

    [
       {
          "id": 3,
       },
       {
          "id": 2,
       }
   ]

Thanks for Your Attention.

0

There are 0 answers