Home Java javaTutorial Examples of JSON parsing and serialization using Jackson under Java

Examples of JSON parsing and serialization using Jackson under Java

Feb 16, 2017 pm 04:47 PM

This article mainly introduces examples of JSON parsing and serialization using Jackson under Java. It has certain reference value. Interested friends can refer to it.

Common Json class libraries under Java include Gson, JSON-lib and Jackson, etc. Jackson is relatively efficient. In the project, Jackson is mainly used to convert JSON and Java objects. Here are some JSON of Jackson How to do it.

1. Preparation

First go to the official website to download the Jackson toolkit. Jackson has 1.x series and 2.x series. As of now, the latest version of the 2.x series is 2.2.3. The 2.x series has 3 jar packages that need to be downloaded:

jackson-core -2.2.3.jar

jackson-annotations-2.2.3.jar

jackson-databind-2.2.3.jar

//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; 
  } 
}
Copy after login

2. Convert JAVA object to JSON [JSON serialization]

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<User> users = new ArrayList<User>(); 
    users.add(user); 
    String jsonlist = mapper.writeValueAsString(users); 
    System.out.println(jsonlist); 
  } 
}
Copy after login

3. JSON to Java class [JSON deserialization]

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); 
  } 
}
Copy after login

4. JSON annotations

Jackson provides a series of annotations to facilitate control of JSON serialization and deserialization. Here are some commonly used annotations.

@JsonIgnore This annotation is used on attributes to ignore the attribute when performing JSON operations.

@JsonFormat This annotation is used on attributes. Its function is to directly convert the Date type into the desired format, such as @JsonFormat(pattern = "yyyy-MM-dd HH-mm-ss") .

@JsonProperty This annotation is used on properties. Its function is to serialize the name of the property into another name. For example, the trueName property is serialized into 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; 
  } 
}
Copy after login

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"} 
  } 
}
Copy after login

The above is the entire content of this article, I hope it will be helpful to everyone’s study , I also hope that everyone will support the PHP Chinese website.

For more articles related to JSON parsing and serialization examples using Jackson under Java, please pay attention to the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How does Java's classloading mechanism work, including different classloaders and their delegation models? How does Java's classloading mechanism work, including different classloaders and their delegation models? Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache? Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading? Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution? Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management? Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

See all articles