Home > Java > javaTutorial > body text

Analyze the serialization and data generic binding of objects in Java's Jackson library

高洛峰
Release: 2017-01-18 10:48:36
Original
1379 people have browsed it

Jackson Object Serialization
Here we will introduce serializing Java objects to a JSON file, and then reading the JSON file to obtain and convert it into an object. In this example, the Student class is created. Create a student.json file that will have student objects represented as JSON.

Create a Java class file named JacksonTester in C:\>Jackson_WORKSPACE.

File: JacksonTester.java

import java.io.File;
import java.io.IOException;
 
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
 
public class JacksonTester {
  public static void main(String args[]){
   JacksonTester tester = new JacksonTester();
   try {
     Student student = new Student();
     student.setAge(10);
     student.setName("Mahesh");
     tester.writeJSON(student);
 
     Student student1 = tester.readJSON();
     System.out.println(student1);
 
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
     e.printStackTrace();
   }
  }
 
  private void writeJSON(Student student) throws JsonGenerationException, JsonMappingException, IOException{
   ObjectMapper mapper = new ObjectMapper(); 
   mapper.writeValue(new File("student.json"), student);
  }
 
  private Student readJSON() throws JsonParseException, JsonMappingException, IOException{
   ObjectMapper mapper = new ObjectMapper();
   Student student = mapper.readValue(new File("student.json"), Student.class);
   return student;
  }
}
 
class Student {
  private String name;
  private int age;
  public Student(){}
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public int getAge() {
   return age;
  }
  public void setAge(int age) {
   this.age = age;
  }
  public String toString(){
   return "Student [ name: "+name+", age: "+ age+ " ]";
  } 
}
Copy after login

Verify the results

Use javac compiles the following class:

C:\Jackson_WORKSPACE>javac JacksonTester.java
Copy after login
Copy after login

Now run jacksonTester to see the result:

C:\Jackson_WORKSPACE>java JacksonTester
Copy after login
Copy after login

Verify the output result

Student [ name: Mahesh, age: 10 ]
Copy after login

Jackson data binding generics
In simple data In binding, we use String as the key object and as a value object mapping class. Instead, we can use concrete Java objects and typecast to JSON for use.


#Consider the following example using a class UserData to save user-specific data.

Create a file named JacksonTester in the Java class file directory C:\>Jackson_WORKSPACE.

File name: JacksonTester.java

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import org.codehaus.jackson.JsonGenerationException;
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
 
public class JacksonTester {
  public static void main(String args[]){
   JacksonTester tester = new JacksonTester();
     try {
      ObjectMapper mapper = new ObjectMapper();
 
      Map userDataMap = new HashMap();
      UserData studentData = new UserData(); 
      int[] marks = {1,2,3};
 
      Student student = new Student();
      student.setAge(10);
      student.setName("Mahesh");
      // JAVA Object
      studentData.setStudent(student);
      // JAVA String
      studentData.setName("Mahesh Kumar");
      // JAVA Boolean
      studentData.setVerified(Boolean.FALSE);
      // Array
      studentData.setMarks(marks);
      TypeReference ref = new TypeReference>() { };
      userDataMap.put("studentData1", studentData);
      mapper.writeValue(new File("student.json"), userDataMap);
      //{
      //  "studentData1":
      // {
      // "student":
      // {
      //  "name":"Mahesh",
      //  "age":10
      //   },
      //   "name":"Mahesh Kumar",
      //   "verified":false,
      //   "marks":[1,2,3]
      //  }
      //}
      userDataMap = mapper.readValue(new File("student.json"), ref);
 
      System.out.println(userDataMap.get("studentData1").getStudent());
      System.out.println(userDataMap.get("studentData1").getName());
      System.out.println(userDataMap.get("studentData1").getVerified());
      System.out.println(Arrays.toString(userDataMap.get("studentData1").getMarks()));
   } catch (JsonParseException e) {
     e.printStackTrace();
   } catch (JsonMappingException e) {
     e.printStackTrace();
   } catch (IOException e) {
      e.printStackTrace();
   }
  }
}
 
class Student {
  private String name;
  private int age;
  public Student(){}
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public int getAge() {
   return age;
  }
  public void setAge(int age) {
   this.age = age;
  }
  public String toString(){
   return "Student [ name: "+name+", age: "+ age+ " ]";
  } 
}
 
class UserData {
  private Student student;
  private String name;
  private Boolean verified;
  private int[] marks;
 
  public UserData(){}
 
  public Student getStudent() {
   return student;
  }
  public void setStudent(Student student) {
   this.student = student;
  }
  public String getName() {
   return name;
  }
  public void setName(String name) {
   this.name = name;
  }
  public Boolean getVerified() {
   return verified;
  }
  public void setVerified(Boolean verified) {
   this.verified = verified;
  }
  public int[] getMarks() {
   return marks;
  }
  public void setMarks(int[] marks) {
   this.marks = marks;
  } 
}
Copy after login

Verification output

Use javac to compile the following class:

C:\Jackson_WORKSPACE>javac JacksonTester.java
Copy after login
Copy after login

Now run jacksonTester to see the results:

C:\Jackson_WORKSPACE>java JacksonTester
Copy after login
Copy after login

Verification output

Student [ name: Mahesh, age: 10 ]
Mahesh Kumar
false
[1, 2, 3]
Copy after login

More Jackson libraries for parsing Java For articles related to object serialization and data generic binding, please pay attention to the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!