JSON(JavaScript Object Notation)是一種輕量級的數(shù)據(jù)交換格式,在前后端數(shù)據(jù)交互中得到廣泛應(yīng)用。Java中可以通過工具類或者手動方式實現(xiàn)JSON和Java對象之間的轉(zhuǎn)換。
將Java對象轉(zhuǎn)換成JSON格式:
//導(dǎo)入Jackson庫 import com.fasterxml.jackson.databind.ObjectMapper; public class Student { private String name; private Integer age; private String[] hobbies; //省略getter、setter方法 } //將Student對象轉(zhuǎn)成JSON格式的字符串 ObjectMapper objectMapper = new ObjectMapper(); Student student = new Student(); student.setName("張三"); student.setAge(18); student.setHobbies(new String[]{"游泳","閱讀"}); String jsonString = objectMapper.writeValueAsString(student); System.out.println(jsonString);
將JSON格式字符串轉(zhuǎn)換成Java對象:
//將JSON格式字符串轉(zhuǎn)成Student對象 ObjectMapper objectMapper = new ObjectMapper(); String jsonString = "{\"name\":\"張三\",\"age\":18,\"hobbies\":[\"游泳\",\"閱讀\"]}"; Student student = objectMapper.readValue(jsonString, Student.class); System.out.println(student.getName()); System.out.println(student.getAge()); System.out.println(Arrays.toString(student.getHobbies()));
以上代碼演示了將Java對象轉(zhuǎn)換成JSON格式字符串以及將JSON格式字符串轉(zhuǎn)換成Java對象的過程。需要注意的是,在使用Jackson庫進行JSON和Java對象轉(zhuǎn)換時,Java對象需要具備getter、setter方法。