zoukankan      html  css  js  c++  java
  • Java下利用Jackson进行JSON解析和序列化

    Jackson是一个功能强大的Java序列化库。除了支持常用的json,同时还支持Smile,BSON,XML,CSV,YAML。
    Jackson的json库提供了3种API:
    • Streaming API : 性能最好
    • Tree Model : 最灵活
    • Data Binding : 最方便
    其中最常用到的就是Data Binding了,基本的用法如下
    ObjectMapper mapper = new ObjectMapper();
    String json = mapper.writeValueAsString(foo);
    Foo foo = mapper.readValue(json, Foo.class);
     
    ObjectMapper是线程安全的,应该尽量的重用。
    需要注意的是,Jackson是基于JavaBean来序列化属性的,如果属性没有GETTER方法,默认是不会输出该属性的。
    但是在序列化的时候,经常会有特殊的需求来对输出的结果进行自定义。
    比如不输出某几个属性,或者自定义属性的名字,等等。
    一、准备工作
     
         1、去官网下载Jackson工具包,下载地址http://wiki.fasterxml.com/JacksonDownload。Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.2.3,2.x系列有3个jar包需要下载:
     
    jackson-core-2.2.3.jar(核心jar包)
     
    jackson-annotations-2.2.3.jar(该包提供Json注解支持)
     
    jackson-databind-2.2.3.jar
     
      2、定义一个java类:
     
      public class User {
            private String name;
            private Integer age;
            private Date birthday;
            private String email;
            
            public String getName() {
                return name;
            }
            public void setName(String name) {
                this.name = name;
            }
            
            public Integer getAge() {
                return age;
            }
            public void setAge(Integer age) {
                this.age = age;
            }
            
            public Date getBirthday() {
                return birthday;
            }
            public void setBirthday(Date birthday) {
                this.birthday = birthday;
            }
            
            public String getEmail() {
                return email;
            }
            public void setEmail(String email) {
                this.email = email;
            }
        }
     
    二、JAVA对象转JSON---[JSON序列化]
      
    public class JacksonDemo {
        public static void main(String[] args) throws ParseException, IOException {
            User user = new User();
            user.setName("小民");    
            user.setEmail("xiaomin@sina.com");
            user.setAge(20);
            
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(dateformat.parse("1996-10-01"));        
            
            /**
             * ObjectMapper是JSON操作的核心,Jackson的所有JSON操作都是在ObjectMapper中实现。
             * ObjectMapper有多个JSON序列化的方法,可以把JSON字符串保存File、OutputStream等不同的介质中。
             * writeValue(File arg0, Object arg1)把arg1转成json序列,并保存到arg0文件中。
             * writeValue(OutputStream arg0, Object arg1)把arg1转成json序列,并保存到arg0输出流中。
             * writeValueAsBytes(Object arg0)把arg0转成json序列,并把结果输出成字节数组。
             * writeValueAsString(Object arg0)把arg0转成json序列,并把结果输出成字符串。
             */
            ObjectMapper mapper = new ObjectMapper();
            
            //User类转JSON
            //输出结果:{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}
            String json = mapper.writeValueAsString(user);
            System.out.println(json);
            
            //Java集合转JSON
            //输出结果:[{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}]
            List<User> users = new ArrayList<User>();
            users.add(user);
            String jsonlist = mapper.writeValueAsString(users);
            System.out.println(jsonlist);
        }
    }
     
    三、JSON转Java类---[JSON反序列化]
     
    public class JacksonDemo {
        public static void main(String[] args) throws ParseException, IOException {
            String json = "{"name":"小民","age":20,"birthday":844099200000,"email":"xiaomin@sina.com"}";
            
            /**
             * ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
             */
            ObjectMapper mapper = new ObjectMapper();
            User user = mapper.readValue(json, User.class);
            System.out.println(user);
        }
    }
     
    四、JSON注解:Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
     
       @JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
     
       @JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
     
       @JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。
     
    public class User {
        private String name;
        
        //不JSON序列化年龄属性
        @JsonIgnore
        private Integer age;
        
        //格式化日期属性
        @JsonFormat(pattern = "yyyy年MM月dd日")
        private Date birthday;
        
        //序列化email属性为mail
        @JsonProperty("mail")
        private String email;
        
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        
        public Integer getAge() {
            return age;
        }
        public void setAge(Integer age) {
            this.age = age;
        }
        
        public Date getBirthday() {
            return birthday;
        }
        public void setBirthday(Date birthday) {
            this.birthday = birthday;
        }
        
        public String getEmail() {
            return email;
        }
        public void setEmail(String email) {
            this.email = email;
        }
    }
     
    public class JacksonDemo {
        public static void main(String[] args) throws ParseException, IOException {
            User user = new User();
            user.setName("小明");    
            user.setEmail("xiaoming@sina.com");
            user.setAge(20);
            
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd");
            user.setBirthday(dateformat.parse("1996-10-01"));        
            
            ObjectMapper mapper = new ObjectMapper();
            String json = mapper.writeValueAsString(user);
            System.out.println(json);
     
            //输出结果:{"name":"小明","birthday":"1996年09月30日","mail":"xiaomin@sina.com"}
        }
    }
     
     
     
     
     
     
  • 相关阅读:
    项目中使用Redis的游标scan的一些小问题
    mac上使用Sequel Pro工具SSH连接数据库
    virtualbox通过Nat模式上网,宿主机与宿主机互通
    Mac系统docker初探
    QQ互联,填写回调时注意事项
    Centos中编辑php扩展库
    samba服务介绍
    bash常用功能
    vsftp服务介绍与相关实验
    shell概述与echo命令
  • 原文地址:https://www.cnblogs.com/lone5wolf/p/10940869.html
Copyright © 2011-2022 走看看