• 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;
        }
    
    
    }
    阁下何不同风起,扶摇直上九万里。
  • 相关阅读:
    程序员写 2000 行 if else?领导:这个锅我不背
    var_dump
    CURL常用命令
    Socket阻塞模式和非阻塞模式的区别
    php框架之odp(一)
    git命令之git clone用法
    git push origin master和git push有什么区别?
    YouTube上最火的十个大数据视频
    Java两种核心机制
    Java四类八种数据类型
  • 原文地址:https://www.cnblogs.com/mlyun/p/10840181.html
Copyright © 2020-2023  润新知