将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; } }
阁下何不同风起,扶摇直上九万里。