JSON数据和Java对象转换
运行结果
package com.itheima.json;
import com.alibaba.fastjson.JSON;
public class FastJsonDemo {
public static void main(String[] args) {
// 1.将Java对象转换位JSON字符串
User user = new User();
user.setId(1);
user.setUsername("zhangsan");
user.setPassword("123");
// 使用JSON类,将User类的对象转换位JSON字符串
String jsonString = JSON.toJSONString(user);
System.out.println(jsonString); // {"id":1,"password":"123","username":"zhangsan"}
// 2. 将JSON字符串转为JAVA对象 这里后面的参数是转换为User类的对象
User u = JSON.parseObject("{\"id\":1,\"password\":\"123\",\"username\":\"zhangsan\"}", User.class);
System.out.println(u); // User{id=1, username='zhangsan', password='123'}
}
}