JSON数据和Java对象转换

image.pngimage.png

运行结果

  1. package com.itheima.json;
  2. import com.alibaba.fastjson.JSON;
  3. public class FastJsonDemo {
  4. public static void main(String[] args) {
  5. // 1.将Java对象转换位JSON字符串
  6. User user = new User();
  7. user.setId(1);
  8. user.setUsername("zhangsan");
  9. user.setPassword("123");
  10. // 使用JSON类,将User类的对象转换位JSON字符串
  11. String jsonString = JSON.toJSONString(user);
  12. System.out.println(jsonString); // {"id":1,"password":"123","username":"zhangsan"}
  13. // 2. 将JSON字符串转为JAVA对象 这里后面的参数是转换为User类的对象
  14. User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class);
  15. System.out.println(u); // User{id=1, username='zhangsan', password='123'}
  16. }
  17. }