Java Jackson @JsonView Json视图

2019-07-05  本文已影响0人  MicoCube
package jackson;

import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Test;

/**
 * @author micocube
 * projectName: utils4j
 * packageName: jackson
 * email: ldscube@gmail.com
 * createTime: 2019-07-05 14:12
 * version: 0.1
 * description:
 */
public class JsonViewTest {


    public interface SimpleView{};
    public interface DetailView extends SimpleView{} ;


    private static class User{
        static ObjectMapper objectMapper = new ObjectMapper();


        private String age;
        @JsonView(SimpleView.class)
        private String userName;
        @JsonView(DetailView.class)
        private String password;
        private String sex;




        public static String getSimpleView()throws Exception{
            User user = getUser();
            return objectMapper.writerWithView(SimpleView.class).writeValueAsString(user);
        }


        /**
         * @return
         * @throws Exception
         */
        public static String getDetailView()throws Exception{
            User user = getUser();
            // 使用SpringMVC的话,可以不用这么写,直接配置MappingJackson2HttpMessageConverter转换器就行
            // AbstractJackson2HttpMessageConverter/writeInternal:196行
            return objectMapper.writerWithView(DetailView.class).writeValueAsString(user);
        }

        private static User getUser() {
            User user = new User();
            user.setAge("11111");
            user.setPassword("pwd");
            user.setSex("man");
            user.setUserName("name");
            return user;
        }


        public String getAge() {
            return age;
        }

        public User setAge(String age) {
            this.age = age;
            return this;
        }

        public String getUserName() {
            return userName;
        }

        public User setUserName(String userName) {
            this.userName = userName;
            return this;
        }

        public String getPassword() {
            return password;
        }

        public User setPassword(String password) {
            this.password = password;
            return this;
        }

        public String getSex() {
            return sex;
        }

        public User setSex(String sex) {
            this.sex = sex;
            return this;
        }
    }





    @Test
    public void test(){

        try {
            System.out.println(User.getSimpleView());
            System.out.println(User.getDetailView());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }


}

{"age":"11111","userName":"name","sex":"man"}
{"age":"11111","userName":"name","password":"pwd","sex":"man"}
上一篇下一篇

猜你喜欢

热点阅读