


Analyze the serialization and data generic binding of objects in Java's Jackson library
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+ " ]"; } }
Verify the results
Use javac compiles the following class:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run jacksonTester to see the result:
C:\Jackson_WORKSPACE>java JacksonTester
Verify the output result
Student [ name: Mahesh, age: 10 ]
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; } }
Verification output
Use javac to compile the following class:
C:\Jackson_WORKSPACE>javac JacksonTester.java
Now run jacksonTester to see the results:
C:\Jackson_WORKSPACE>java JacksonTester
Verification output
Student [ name: Mahesh, age: 10 ] Mahesh Kumar false [1, 2, 3]
More Jackson libraries for parsing Java For articles related to object serialization and data generic binding, please pay attention to the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics











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

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{&

[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

TheJSONJacksonisalibraryforJava.IthasverypowerfuldatabindingcapabilitiesandprovidesaframeworktoserializecustomjavaobjectstoJSONanddeserializeJSONbacktoJavaobject.WecanalsoconvertanXMLformattothePOJOobjectusingthereadValue()methodoftheXmlMapper&nb

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

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

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

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
