search
HomeJavajavaTutorialAnalyze 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!

Statement
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
在Java中使用Jackson库将CSV转换为JSON?在Java中使用Jackson库将CSV转换为JSON?Aug 18, 2023 pm 11:49 PM

AJackson 是一个提供了多种不同方式来处理JSON的Java JSONAPI。我们可以使用CsvMapper 类将CSV数据转换为JSON数据,它是一个特殊的ObjectMapper,具有扩展功能,可以将POJOs转换为CsvSchema 实例。我们可以使用 reader() 方法构建具有默认设置的ObjectReader。为了进行转换,我们需要导入com.fasterxml.jac

在Java中使用Jackson库将POJO转换为XML?在Java中使用Jackson库将POJO转换为XML?Sep 18, 2023 pm 02:21 PM

Jackson是一个基于Java的库,它对于将Java对象转换为JSON以及将JSON转换为Java对象非常有用。JacksonAPI比其他API更快,需要更少的内存区域,并且适合大型对象。我们使用XmlMapper类的writeValueAsString()方法将POJO转换为XML格式,并且需要将相应的POJO实例作为参数传递给此方法。语法publicStringwriteValueAsString(Objectvalue)throwsJsonProcessingException示例imp

在Java中使用Jackson库将XML转换为POJO?在Java中使用Jackson库将XML转换为POJO?Aug 30, 2023 am 10:21 AM

TheJSONJacksonisalibraryforJava.IthasverypowerfuldatabindingcapabilitiesandprovidesaframeworktoserializecustomjavaobjectstoJSONanddeserializeJSONbacktoJavaobject.WecanalsoconvertanXMLformattothePOJOobjectusingthereadValue()methodoftheXmlMapper&nb

SpringBoot升级指定jackson版本的问题怎么解决SpringBoot升级指定jackson版本的问题怎么解决May 12, 2023 pm 02:13 PM

【漏洞通告】2月19日,NVD发布安全通告披露了jackson-databind由JNDI注入导致的远程代码执行漏洞(CVE-2020-8840),CVSS评分为9.8。受影响版本的jackson-databind中由于缺少某些xbean-reflect/JNDI黑名单类,如org.apache.xbean.propertyeditor.JndiConverter,可导致攻击者使用JNDI注入的方式实现远程代码执行。目前厂商已发布新版本完成漏洞修复,请相关用户及时升级进行防护。由于项目中用到的S

如何使用Jackson在Java中将JSON对象转换为枚举类型?如何使用Jackson在Java中将JSON对象转换为枚举类型?Sep 05, 2023 pm 12:13 PM

JSONObject可以解析字符串中的文本以生成Map类型的对象。枚举可用于定义常量集合,当我们需要一个不代表某种数字或文本数据的预定义值列表时,我们可以使用枚举。我们可以使用ObjectMapper类的readValue()方法将JSON对象转换为枚举。在下面的示例中,我们可以使用Jackson库将JSON对象转换/反序列化为Java枚举。示例importcom.fasterxml.jackson.databind.*;publicclassJSONToEnumTest{ &

如何在Java中使用Jackson获取JSONParser的默认设置?如何在Java中使用Jackson获取JSONParser的默认设置?Sep 12, 2023 am 11:57 AM

所有JSON&nbsp;解析器的默认设置都可以使用JsonParser.Feature枚举来表示。JsonParser.Feature.values()将返回所有可用于JSONParser&nbsp;的功能,但是特定解析器是否启用或禁用某个功能可以使用JsonParser的isEnabled()方法来确定。语法publicstaticenumJsonParser.FeatureextendsEnum<JsonParser.Feature>示例importcom.fas

在Java中使用Jackson时何时使用@ConstructorProperties注解?在Java中使用Jackson时何时使用@ConstructorProperties注解?Aug 27, 2023 pm 08:53 PM

@ConstructorProperties注解来自java.bean包,用于通过带注解的构造函数将JSON反序列化为java对象。此注释从Jackson2.7版本开始支持。此注释的工作方式非常简单,我们可以提供一个包含每个构造函数参数的属性名称的数组,而不是注释构造函数中的每个参数。语法@Documented@Target(value=CONSTRUCTOR)@Retention(value=RUNTIME)public@interfaceConstructorProperties示例impo

Java怎么用Jackson序列化实现数据脱敏Java怎么用Jackson序列化实现数据脱敏Apr 18, 2023 am 09:46 AM

1.背景在项目中有些敏感信息不能直接展示,比如客户手机号、身份证、车牌号等信息,展示时均需要进行数据脱敏,防止泄露客户隐私。脱敏即是对数据的部分信息用脱敏符号(*)处理。2.目标在服务端返回数据时,利用Jackson序列化完成数据脱敏,达到对敏感信息脱敏展示。降低重复开发量,提升开发效率形成统一有效的脱敏规则可基于重写默认脱敏实现的desensitize方法,实现可扩展、可自定义的个性化业务场景的脱敏需求3.主要实现3.1基于Jackson的自定义脱敏序列化实现StdSerializer:所有标

See all articles

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.