一:fastjson作用
1.将Java对象转换为json字符串====》响应给前端。
2.将json字符串转换为Java对象 ====》接受前端的json数据封装到对象中。
二:常用API
fastjson API 入口类是 com.alibaba.fastjson.JSON ,常用的序列化操作都可以在JSON类上的静态方法直接完成
1.在pom.xml下导入依赖
<dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.47</version></dependency>
2.在test包下创建User实体类
public class User {private String username;private String password;public User(){}public User(String username, String password) {this.username = username;this.password = password;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}@Overridepublic String toString() {return "User{" +"username='" + username + '\'' +", password='" + password + '\'' +'}';}
}
三:fastjson案例
1.将实体类转换为json字符串
@Testpublic void tset1(){//创建User对象User user = new User();//添加数据user.setUsername("李知恩");user.setPassword("zhienaini");/*** 使用fastjson的核心类JSON调用方法*/String jsonString = JSON.toJSONString(user);System.out.println("jsonString = " + jsonString);//打印结果:/*** jsonString = {"password":"zhienaini","username":"李知恩"}*/}
运行结果如下 :
2 .将单列集合转换为json字符串
//将单列集合转换为json字符串@Testpublic void test2(){//创建集合对象ArrayList<Object> list = new ArrayList<>();//添加数据Collections.addAll(list,new User("张三","123456"),new User("李四","1254360"),new User("王五","789456"));//使用fastjson的核心类JSON调用方法String s = JSON.toJSONString(list);System.out.println("s = " + s);//打印结果:/*** s = [* {"password":"123456","username":"张三"},* {"password":"1254360","username":"李四"},* {"password":"789456","username":"王五"}* ]*/}
3.将双列集合转换为json字符串
//将双列集合转换为json字符串@Testpublic void test3(){//创建Map集合对象HashMap<Object, Object> hashMap = new HashMap<>();//添加数据hashMap.put("00001","库里");hashMap.put("00002",new User("哈登","1234"));//Map里面嵌套list集合List<Object> list1 = new ArrayList<>();Collections.addAll(list1,new User("库里1","159753"),new User("哈登1","156234"),new User("詹姆斯1","78456"));hashMap.put("00003",list1);//使用fastjson的核心类JSON调用方法String s = JSON.toJSONString(hashMap);System.out.println("s = " + s);//打印结果:/*** s = {"00002":{"password":"1234","username":"哈登"},* "00003":[{"password":"159753","username":"库里1"},{"password":"156234","username":"哈登1"},{"password":"78456","username":"詹姆斯1"}],* "00001":"库里"}*/}