【转载】Java下利用Jackson进行JSON解析和序列化

参考资料:

https://blog.csdn.net/sdut406/article/details/85647982

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

一、准备工作

Jackson有1.x系列和2.x系列,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依赖就够了

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>

aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAWcAAABBCAIAAACCWPJFAAAHCUlEQVR4nO2csZLbNhCG/VwcW7m8wimKZlK5yGRyI026NFdIqlO4ES+Vyoiu0qgLUOYF3KfKpEneIgVFcAEsQECiSJD4PV8h60hxd7n6uYDP/7v3X30NAADhvBs9AgDAtIBqAADigGoAAOIIVY1/fv1U8+Xj8+hBAwBGZAKqUSzWu0pIKY+bp9Hr1YS0PYryZdHGU6wOZ1HtVqER1kmlk1FQzMnnWGxKUR2Wixuv6Ao4KvE7Y5gEvGqcTqfT6fT6+qpejKgay30lyu3olaJANdLMMVnVKFaHsxBSSvbh91JefySlZM5dbI9CSCmF3nIjEqoa//3+ueavn78fOMSXUpz36/DjB2hWWzXiP2F6qpF+jn7V6Iynl4DtGIrF9ti8U6wOZ6tzPB1eLNa76nr8SykSeXzeMmt8+vPvmu9+OQ8QIlRjokA1HJcwx5bADk9n7cOrxuVyuVwub29v6gVVjc9f/q356bc/rKJcpykpZV0I+o4asYrF9iiq3eY6th03T8WmpGfRgtJz2Ulvua/UMT9+2LSXqw7LxRMXUt0c26MQojr8sK9UYLWcd4bnWKE02XFBGmHQBq2Prx8jNBdSK0cB93zRYm6EVgq+XM18nlqO9kXphG9EqF2iztRKgVZDe79J3BUSGwO7rmGfN0aTu76rsY/PoVXjtlmjrh1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xL9heYOzcVqzBpyK6Ws4FY+eIwnJNhy+RzWsFgoyPXapRkcitA5Garc5G9MYht7XgFMxnIrfT8Kp2BlJmGoElKXb9NizQvHeLLMOvTgbdz0yH6gacCqGU7GcglMxG0m4argu/b7L01g7IHA31Lq0UYe+nI3tWz+QaiT1L6+TIAcX3xxyzAeoxvjk4OKbQ4750L9qgHBycPHNIcfcgGoAAOKAagAA4oBqAADigGoAAOKAagAA4oBqAADigGoAAOIYQjXgNgzAnJi5asBtOBFyyDEfhv6N8oHTg9twIuSQo57s/X6/6f427RCqAbdh/RLwDZ1zjsW9fr+aoeTo6bDM/H+vQTUmyjxyjPX71c71OlyMS0r+GnAbdgy3AzvxBt+I6bsNPyBT6/Mj/H6Nw6IeeEOSyqwBt+FEnHhzcht+SKZs+7Gw7gFKUlOes5JRDbgNw214WLfhB2VKey/W79c8PZ8VCtyG4TZsk1SOD81UNd4Nfr/hPx2XZGYNuA3DbXhgt+EHZXqP3+/qcCb+tRnNGnAbhtuwnILb8KMyvc/v197uTZBUZo2cycGJN4cc8wGqMT4pz6LIEdj0rxognByceHPIMTegGgCAOKAaAIA4oBoAgDigGgCAOKAaAIA4/gcku/JB9RULLgAAAABJRU5ErkJggg==" alt="" />

【转载】Java下利用Jackson进行JSON解析和序列化
import java.util.Date;

/**
* JSON序列化和反序列化使用的User类
*/
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;
} @Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", email='" + email + '\'' +
'}';
}
}
【转载】Java下利用Jackson进行JSON解析和序列化

二、JAVA对象转JSON[JSON序列化]

【转载】Java下利用Jackson进行JSON解析和序列化
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import com.fasterxml.jackson.databind.ObjectMapper; public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("zhangsan");
user.setEmail("zhangsan@163.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":"zhangsan","age":20,"birthday":844099200000,"email":"zhangsan@163.com"}
String json = mapper.writeValueAsString(user);
System.out.println(json); //Java集合转JSON
//输出结果:[{"name":"zhangsan","age":20,"birthday":844099200000,"email":"zhangsan@163.com"}]
List<User> users = new ArrayList<User>();
users.add(user);
String jsonlist = mapper.writeValueAsString(users);
System.out.println(jsonlist);
}
}
【转载】Java下利用Jackson进行JSON解析和序列化

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

【转载】Java下利用Jackson进行JSON解析和序列化
public class JacksonDemo {
public static void main(String[] args) throws ParseException, IOException {
String json = "{\"name\":\"zhangsan\",\"age\":20,\"birthday\":844099200000,\"email\":\"zhangsan@163.com\"}";
/**
* ObjectMapper支持从byte[]、File、InputStream、字符串等数据的JSON反序列化。
*/
ObjectMapper mapper = new ObjectMapper();
User user = mapper.readValue(json, User.class);
System.out.println(user);
}
}
【转载】Java下利用Jackson进行JSON解析和序列化

结果

User{name='zhangsan', age=20, birthday=Tue Oct 01 00:00:00 CST 1996, email='zhangsan@163.com'}
【转载】Java下利用Jackson进行JSON解析和序列化
public class JacksonDemo {

    public static ObjectMapper mapper = new ObjectMapper();

    public static void main(String[] args) throws ParseException, IOException {
String json = "[{\"name\":\"zhangsan\",\"age\":20,\"birthday\":844099200000,\"email\":\"zhangsan@163.com\"}]";
List<User> beanList = mapper.readValue(json, new TypeReference<List<User>>() {});
System.out.println(beanList);
} }
【转载】Java下利用Jackson进行JSON解析和序列化

结果

[User{name='zhangsan', age=20, birthday=Tue Oct 01 00:00:00 CST 1996, email='zhangsan@163.com'}]

四、JSON注解

Jackson提供了一系列注解,方便对JSON序列化和反序列化进行控制,下面介绍一些常用的注解。
@JsonIgnore 此注解用于属性上,作用是进行JSON操作时忽略该属性。
@JsonFormat 此注解用于属性上,作用是把Date类型直接转化为想要的格式,如@JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss")。
@JsonProperty 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称,如把trueName属性序列化为name,@JsonProperty("name")。

【转载】Java下利用Jackson进行JSON解析和序列化
import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty; import java.util.Date; /**
* JSON序列化和反序列化使用的User类
*/
public class User { private String name; //不JSON序列化年龄属性
@JsonIgnore
private Integer age; //格式化日期属性
@JsonFormat(pattern = "yyyy年MM月dd日")
private Date birthday; //序列化email属性为mail
@JsonProperty("my_email")
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;
} @Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
", email='" + email + '\'' +
'}';
}
}
【转载】Java下利用Jackson进行JSON解析和序列化
【转载】Java下利用Jackson进行JSON解析和序列化
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat; public class JacksonDemo { public static void main(String[] args) throws ParseException, IOException {
User user = new User();
user.setName("zhangsan");
user.setEmail("zhangsan@163.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);
}
}
【转载】Java下利用Jackson进行JSON解析和序列化
{"name":"zhangsan","birthday":"1996年09月30日","my_email":"zhangsan@163.com"}
上一篇:使用jackson解析JSON数据


下一篇:Java下用Jackson进行JSON序列化和反序列化(转)