Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JsonView does not work

Tags:

json

spring

I use the annotation @JsonView, but it doesn't work, here is my code and the return data, would you please help me to look where I am wrong.

My spring jar shows the edition of "spring-web-3.2.8.RELEASE.jar", and I just add this bean,I do not know whether it is useful or not, and I just use @JsonView directly in my code

<bean id = "jacksonMessageConverter" class = "org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
        </bean>

Here is the View class

public class View {
    public interface Summary{};
}

This is the User entity class(with "set" "get" method omitted), it has several attribute which corresponding to the database, there is a "status" attribute needn't return in the json data.

public Class User{
    @JsonView(View.Summary.class)
    private Integer uid;

    @JsonView(View.Summary.class)
    private String first;

    @JsonView(View.Summary.class)
    private String last;

    @JsonView(View.Summary.class)
    private String email;

    @JsonView(View.Summary.class)
    private String password;

    private Integer status;

}

I had the controller

@RequestMapping(value="/login", method=RequestMethod.POST)
@JsonView(View.Summary.class)
@ResponseBody
public Message login(String email, String password){        
    User user = userMapper.findUser(email,password);        

    Message message = new Message();                
    message.setUser(user);
    return message;     
}   
}

and here is my Message class with the "set" "get" methods

public class Message {
    private int box_hits;

    private List<Box> boxes;

    @JsonView(View.Summary.class)
    private User user;
}

when I use the postman to test the url,it shows json data, obviously, it should not return with the attribute without @JsonView, what' wrong with my code?

 {
  "box_hits": 0,
  "boxes": null,
  "user": {
    "uid": 1,
    "first": "yuan",
    "last": "kang",
    "email": "[email protected]",
    "password": "123",
    "status": 0
  }
}
like image 680
Alina Avatar asked Oct 03 '15 21:10

Alina


People also ask

What is the use of @JsonView?

@JsonView is used to control values to be serialized or not.

What is JsonView annotation?

The JsonView annotation can be used to include/exclude a property during the serialization and deserialization process dynamically. We need to configure an ObjectMapper class to include the type of view used for writing a JSON from Java object using the writerWithView() method.


Video Answer


1 Answers

As described in the announcement blog post, this feature is only available as of Spring Framework 4.2. It won't work with Spring 3.2.8.

like image 164
Brian Clozel Avatar answered Oct 03 '22 14:10

Brian Clozel