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

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

Jan 18, 2017 am 10:48 AM
jackson

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!

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 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)

Hot Topics

Java Tutorial
1666
14
PHP Tutorial
1272
29
C# Tutorial
1252
24
Convert CSV to JSON using Jackson library in Java? Convert CSV to JSON using Jackson library in Java? Aug 18, 2023 pm 11:49 PM

AJackson is a Java JSON API that provides several different ways to process JSON. We can convert CSV data to JSON data using the CsvMapper class, which is a special ObjectMapper with extended functionality to convert POJOs into CsvSchema instances. We can build an ObjectReader with default settings using the reader() method. In order to convert we need to import com.fasterxml.jac

How to convert JSON object to enum type in Java using Jackson? How to convert JSON object to enum type in Java using Jackson? Sep 05, 2023 pm 12:13 PM

JSONObject can parse text in a string to generate a Map type object. Enumerations can be used to define collections of constants, and we can use enumerations when we need a predefined list of values ​​that does not represent some kind of numeric or textual data. We can convert JSON objects into enumerations using the readValue() method of the ObjectMapper class. In the example below, we can use the Jackson library to convert/deserialize a JSON object into a Java enumeration. Example importcom.fasterxml.jackson.databind.*;publicclassJSONToEnumTest{&

How to solve the problem of specifying jackson version in SpringBoot upgrade How to solve the problem of specifying jackson version in SpringBoot upgrade May 12, 2023 pm 02:13 PM

[Vulnerability Notice] On February 19, NVD issued a security notice disclosing a remote code execution vulnerability (CVE-2020-8840) in jackson-databind caused by JNDI injection, with a CVSS score of 9.8. The affected version of jackson-databind lacks certain xbean-reflect/JNDI blacklist classes, such as org.apache.xbean.propertyeditor.JndiConverter, which can lead to attackers using JNDI injection to achieve remote code execution. At present, the manufacturer has released a new version to complete the vulnerability repair. Relevant users are requested to upgrade in time for protection. Since the S used in the project

Convert XML to POJO using Jackson library in Java? Convert XML to POJO using Jackson library in Java? Aug 30, 2023 am 10:21 AM

TheJSONJacksonisalibraryforJava.IthasverypowerfuldatabindingcapabilitiesandprovidesaframeworktoserializecustomjavaobjectstoJSONanddeserializeJSONbacktoJavaobject.WecanalsoconvertanXMLformattothePOJOobjectusingthereadValue()methodoftheXmlMapper&nb

Convert POJO to XML using Jackson library in Java? Convert POJO to XML using Jackson library in Java? Sep 18, 2023 pm 02:21 PM

Jackson is a Java-based library that is useful for converting Java objects to JSON and JSON to Java objects. JacksonAPI is faster than other APIs, requires less memory area, and is suitable for large objects. We use the writeValueAsString() method of the XmlMapper class to convert the POJO to XML format, and the corresponding POJO instance needs to be passed as a parameter to this method. Syntax publicStringwriteValueAsString(Objectvalue)throwsJsonProcessingExceptionExampleimp

How to use Jackson serialization to achieve data desensitization in Java How to use Jackson serialization to achieve data desensitization in Java Apr 18, 2023 am 09:46 AM

1. Background: Some sensitive information in the project cannot be displayed directly, such as customer mobile phone numbers, ID cards, license plate numbers and other information. Data desensitization is required when displaying to prevent the leakage of customer privacy. Desensitization means treating part of the data with desensitization symbols (*). 2. When the target returns data from the server, use Jackson serialization to complete data desensitization to achieve desensitized display of sensitive information. Reduce the amount of repeated development and improve development efficiency to form unified and effective desensitization rules. It can be based on the desensitize method of rewriting the default desensitization implementation to realize the desensitization requirements of scalable and customizable personalized business scenarios. 3. Main implementation 3.1 Based on Jackson Custom desensitized serialization implementation of StdSerializer: all standard

How to get JSONParser's default settings using Jackson in Java? How to get JSONParser's default settings using Jackson in Java? Sep 12, 2023 am 11:57 AM

The default settings for all JSON parsers can be represented using the JsonParser.Feature enumeration. JsonParser.Feature.values() will return all features available for JSONParser, but whether a feature is enabled or disabled for a specific parser can be determined using JsonParser's isEnabled() method. Syntax publicstaticenumJsonParser.FeatureextendsEnum<JsonParser.Feature>Example importcom.fas

When to use @ConstructorProperties annotation when using Jackson in Java? When to use @ConstructorProperties annotation when using Jackson in Java? Aug 27, 2023 pm 08:53 PM

The @ConstructorProperties annotation comes from the java.bean package and is used to deserialize JSON into java objects through an annotated constructor. This annotation is supported starting from Jackson 2.7. The way this annotation works is very simple, instead of annotating each parameter in the constructor, we can provide an array containing the property names for each constructor parameter. Syntax@Documented@Target(value=CONSTRUCTOR)@Retention(value=RUNTIME)public@interfaceConstructorPropertiesExample impo

See all articles