Jackson - 对象序列化
让我们将 java 对象序列化为 json 文件,然后读取该 json 文件以获取该对象。在此示例中,我们创建了 Student 类。我们将创建一个 Student.json 文件,其中包含 Student 对象的 json 表示形式。
在C:\>Jackson_WORKSPACE中创建一个名为 JacksonTester 的 java 类文件。
文件:JacksonTester.java
导入java.io.File;
导入java.io.IOException;
导入 com.fasterxml.jackson.core.JsonGenerationException;
导入 com.fasterxml.jackson.core.JsonParseException;
导入 com.fasterxml.jackson.databind.JsonMappingException;
导入 com.fasterxml.jackson.databind.ObjectMapper;
公共类 JacksonTester {
公共静态无效主(字符串参数[]){
JacksonTester 测试器 = new JacksonTester();
尝试 {
学生学生=新学生();
学生.setAge(10);
学生.setName("Mahesh");
测试者.writeJSON(学生);
学生student1 = tester.readJSON();
System.out.println(student1);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
私人无效 writeJSON(学生学生)抛出 JsonGenerationException,JsonMappingException,IOException{
ObjectMapper 映射器 = new ObjectMapper();
mapper.writeValue(new File("student.json"), Student);
}
私人学生 readJSON() 抛出 JsonParseException、JsonMappingException、IOException{
ObjectMapper 映射器 = new ObjectMapper();
Student Student = mapper.readValue(new File("student.json"), Student.class);
回国学生;
}
}
班级学生{
私有字符串名称;
私有整数年龄;
公共学生(){}
公共字符串 getName() {
返回名称;
}
公共无效setName(字符串名称){
this.name = 名称;
}
公共 int getAge() {
返回年龄;
}
公共无效setAge(int年龄){
this.age = 年龄;
}
公共字符串 toString(){
return "学生[姓名:"+姓名+",年龄:"+年龄+"]";
}
}
验证结果
使用javac编译器编译类,如下所示:
C:\Jackson_WORKSPACE>javac JacksonTester.java
现在运行 jacksonTester 查看结果:
C:\Jackson_WORKSPACE>java JacksonTester
验证输出
Student [ name: Mahesh, age: 10 ]