博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Java下用Jackson进行JSON序列化和反序列化(转)
阅读量:7050 次
发布时间:2019-06-28

本文共 6240 字,大约阅读时间需要 20 分钟。

Java下常见的Json类库有Gson、JSON-lib和Jackson等,Jackson相对来说比较高效,在项目中主要使用Jackson进行JSON和Java对象转换,下面给出一些Jackson的JSON操作方法。

一、准备工作

首先去官网下载Jackson工具包,下载地址。Jackson有1.x系列和2.x系列,截止目前2.x系列的最新版本是2.9.0,2.x系列有3个jar包需要下载:

jackson-core-2.2.3.jar(核心jar包,)

jackson-annotations-2.2.3.jar(该包提供Json注解支持,)

jackson-databind-2.2.3.jar()

可以使用Maven快速依赖引入:

com.fasterxml.jackson.core
jackson-databind
2.9.0
com.fasterxml.jackson.core
jackson-annotations
2.9.0
com.fasterxml.jackson.core
jackson-core
2.9.0

准备序列化的类:

//JSON序列化和反序列化使用的User类  import java.util.Date;    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序列化]

import java.io.IOException;  import java.text.ParseException;  import java.text.SimpleDateFormat;    import com.fasterxml.jackson.databind.ObjectMapper;    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
users = new ArrayList
(); users.add(user); String jsonlist = mapper.writeValueAsString(users); System.out.println(jsonlist); } }

三、JSON字符串转Java类[JSON反序列化] 

import java.io.IOException;  import java.text.ParseException;  import com.fasterxml.jackson.databind.ObjectMapper;    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")。

import java.util.Date;  import com.fasterxml.jackson.annotation.*;    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;      }  }        import java.io.IOException;  import java.text.ParseException;  import java.text.SimpleDateFormat;    import com.fasterxml.jackson.databind.ObjectMapper;    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 mapper = new ObjectMapper();          String json = mapper.writeValueAsString(user);          System.out.println(json);          //输出结果:{"name":"小民","birthday":"1996年09月30日","mail":"xiaomin@sina.com"}      }  }

其它:

@JsonIgnoreProperties此注解是类注解,作用是json序列化时将java bean中的一些属性忽略掉,序列化和反序列化都受影响。

@JsonIgnore此注解用于属性或者方法上(最好是属性上),作用和上面的@JsonIgnoreProperties一样。

@JsonFormat此注解用于属性或者方法上(最好是属性上),可以方便的把Date类型直接转化为我们想要的模式,比如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")

@JsonSerialize此注解用于属性或者getter方法上,用于在序列化时嵌入我们自定义的代码,比如序列化一个double时在其后面限制两位小数点。

@JsonDeserialize此注解用于属性或者setter方法上,用于在反序列化时可以嵌入我们自定义的代码,类似于上面的@JsonSerialize

五、抛砖引玉

除了String之外,还可以操作byte[]等。大致的方法名和操作String的一致。 

 

参考:

(以上内容转自此篇文章)

转载地址:http://ibpol.baihongyu.com/

你可能感兴趣的文章
SpringBoot RabbitMQ 集成 五 "Topics"
查看>>
Virtual SAN 读取 IO – 缓存/缓冲区/磁盘心轴
查看>>
AS3学习笔记(三)XML解析
查看>>
linux shell中所有括号的用法
查看>>
etcd v2文档(4) -- 客户端http请求管理etcd 版本号和节点状态
查看>>
Android签名总结
查看>>
cisco asa 5520 8.4 (二) -- 动态nat
查看>>
java.io.NotSerializableException
查看>>
实现VARCHART项目管理的技巧分享
查看>>
php中instanceof的作用
查看>>
oracle中 connect by prior 递归算法(层次化查询)
查看>>
javascript 字符串截取
查看>>
育儿 - 数学
查看>>
Bson项目的配置
查看>>
maven 笔记
查看>>
Webpack 笔记
查看>>
启用客服qq的方法
查看>>
秒数自动跳动的JS时间特效
查看>>
Mac OS X Lion 10.7.3 发布
查看>>
Freiburg这么做太愚蠢了
查看>>