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;
        }
    
    
    }
    阁下何不同风起,扶摇直上九万里。
  • 相关阅读:
    LeetCode Reverse Nodes in k-Group
    LeetCode Unique Binary Search Trees II
    Binary Tree Zigzag Level Order Traversal
    JavaWeb--JSP
    Java--面向对象
    javaScript-进阶篇(三)
    javaScript-进阶篇(二)
    java--常用类
    javaScript-进阶篇(一)
    Java--数组
  • 原文地址:https://www.cnblogs.com/mlyun/p/10840181.html
Copyright © 2011-2022 走看看