首页 > 其他 > 详细

Jackson对象序列化

时间:2019-05-09 19:34:04      阅读:112      评论:0      收藏:0      [点我收藏+]
将Java对象序列化到一个JSON文件,然后再读取JSON文件获取转换为对象。在这个例子中,创建了Student类。
import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;

import java.io.File;
import java.io.IOException;

/**
 */
public class JacksonTester2 {
    public static void main(String[] args) {
        JacksonTester2 jackson = new JacksonTester2();
        try {
            Student student = new Student();
            student.setName("张三");
            student.setAge(18);
            jackson.writeJSON(student);

            Student stu = jackson.readJSON();
            System.out.println(stu);
        } catch (JsonParseException e) {
            e.printStackTrace();
        } catch (JsonMappingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //将对象序列化到文件
    private void writeJSON(Student student) throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(new File("student.json"), student);
    }

    //读取文件转换为对象
    private Student readJSON() throws IOException {
        ObjectMapper mapper = new ObjectMapper();
        Student student = mapper.readValue(new File("student.json"), Student.class);
        return student;
    }


}

 

技术分享图片

 

Jackson对象序列化

原文:https://www.cnblogs.com/mlyun/p/10840181.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!