首先要导入Jackson jar包并依赖
java对象转json字符串
public class MyTest {
public static void main(String[] args) throws IOException {
Student student = new Student();
student.setName("张三");
student.setAge(20);
student.setFlag(true);
student.setBirthday(new Date());
//创建对象,有一个核心的对象
ObjectMapper objectMapper = new ObjectMapper();
//调用转换的方法,把java对象转换成json字符串
String jsonStr = objectMapper.writeValueAsString(student);
System.out.println(jsonStr);
objectMapper.writeValue(new FileOutputStream("student.json"),student);
objectMapper.writeValue(new FileWriter("student1.json"),student);
objectMapper.writeValue(new File("student2.txt"),student);
}
}
json字符串转java对象
public class MyTest2 {
public static void main(String[] args) throws IOException {
//json字符串转换成java对象
Student student = new Student();
//{"name":"zhangsan","age":20,"birthday":"new Data()"}
String jsonStr="{\"name\":\"zhangsan\",\"age\":20}";
ObjectMapper objectMapper = new ObjectMapper();
//把json字符串转为java对象
Student student1 = objectMapper.readValue(jsonStr, Student.class);
System.out.println(student1);
}
}