FastJson是一个Java库,可以将Java对象转换为JSON格式,当然它也可以将JSON字符串转换为Java对象
提供了toJSonString()和parseObject()方法来将Java对象与JSON相互转换,调用toJSonString()方法即可将对象转换成JSON字符串
parseObject方法则反过来将JSON字符串转换成对象
- 添加依赖
测试com.alibaba fastjson 1.2.78
实体类:
public class Users {
private int uid; // 用户实体的主键属性
private String uname; // 用户账号
private String upassword; // 用户密码
private String uemail; // 用户邮箱 用于激活使用
private String usex; // 用户性别
private int ustatus; // 用户激活状态 0 未激活 1 激活
private String ucode; // 邮件激活码
private int urole; // 用户 0 管理员 1
// JavaBean...
}
单元测试:
@Test
public void testFastJson() {
Users users = new Users(2022, "coderitl", "coderitl", "123xxx@qq.com", "男", 1, "2022", 2);
// 将实体类转换为 json 格式
String strToJsonUser = JSON.toJSONString(users);
System.out.println(strToJsonUser);
}
输出
Jackson-JSON操作
Jackson是一个能否将Java对象序列化为JSON字符串,也能够将JSON字符串反序列化为Java对象的框架
通过方法readvalue和writevalue实现
使用步骤- 添加依赖或者下载对应jar文件
com.fasterxml.jackson.core jackson-annotations 2.13.0 com.fasterxml.jackson.core jackson-core 2.13.0 com.fasterxml.jackson.core jackson-databind 2.13.0
- 使用
@Test
public void testJackSon() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
Users users = new Users(2022, "coderitl", "coderitl", "123xxx@qq.com", "男", 1, "2022", 2);
String s = mapper.writevalueAsString("testJackSon: "+users);
System.out.println(s);
}
JSON格式字符串转换为实体类
@Test
public void testJackSon() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
// JSON 字符串
String message = "{n" +
"t"uid": 2022,n" +
"t"uname": "coderitl",n" +
"t"upassword": "coderitl",n" +
"t"uemail": "123xxx@qq.com",n" +
"t"usex": "男",n" +
"t"ustatus": 1,n" +
"t"ucode": "2022",n" +
"t"urole": 2n" +
"}";
Users users = mapper.readValue(message, Users.class);
System.out.println(users);
}
浏览器处理JSON
测试
// 对象
const obj = {name: "coder-itl", age: 20, address: "testJson"};
console.log(typeof (obj)); // object
// 将浏览器对象转换为字符串方法
let res = JSON.stringify(obj);
console.log(typeof (res)); // String
// 将字符串转换为 Object
res = JSON.parse(res);
console.log(typeof (res)); // object



