zoukankan      html  css  js  c++  java
  • Jackson对象序列化

    将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;
        }
    
    
    }
    阁下何不同风起,扶摇直上九万里。
  • 相关阅读:
    2019 SDN上机第2次作业
    2019 SDN上机第1次作业
    第07组 团队Git现场编程实战
    第二次结对编程作业
    c语言之问题集
    2019春第2次课程设计实验安排
    2019年十二周总结
    第十一周总结
    第十周作业
    第九周总结
  • 原文地址:https://www.cnblogs.com/mlyun/p/10840181.html
Copyright © 2011-2022 走看看