fastJson是阿里巴巴出品的一个json序列化工具,我们需要下载对应的jar
。
我们可以到Maven中心库下载对应版本的JSON.jar
将对象转换成Json串,可以用下面的方法:
JSON.toJSONString(对象);
将Json串转换成java对象,分为两种情况:
//对象是单个元素
JSON.parseObject(json串,CLAZZ);
//对象包含多个元素
JSON.parseArray(json串,CLAZZ);
下面是转换实例:
List <---->Json
List<String> stringList = new ArrayList<>();
stringList.add("aaa");
stringList.add("bbb");
stringList.add("ccc");
stringList.add("ddd");
//list-->json
String jsonString = JSON.toJSONString(stringList);
//json-->list
List<String> list =JSON.parseArray(jsonString,String.class);
Map <---->Json
Map<String,Integer> map = new HashMap<>();
map.put("zhangsan", 18);
map.put("lisi", 28);
map.put("wangwu", 38);
//map-->json
String jsonString2 = JSON.toJSONString(map);
//json-->map
Map<String,Integer> map2 =JSON.parseObject(jsonString2,Map.class);
JavaBean <------> Json
User.java
package fastjson;
public class User {
private String name;
private String age;
public User(String name, String age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@Override
public String toString() {
return "User [name=" + name + ", age=" + age + "]";
}
}
UserGroup.java
package fastjson;
import java.util.ArrayList;
import java.util.List;
public class UserGroup {
private String name;
List<User> userList = new ArrayList<>();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
@Override
public String toString() {
return "UserGroup [name=" + name + ", userList=" + userList + "]";
}
}
测试类:
package fastjson;
import java.util.List;
import com.alibaba.fastjson.JSON;
public class FastJsonTest {
public static void main(String[] args) {
// 构建用户geust
User guestUser = new User("guest","18");
// 构建用户root
User rootUser = new User("root","28");
// 构建用户组对象
UserGroup group = new UserGroup();
group.setName("admin");
group.getUserList().add(guestUser);
group.getUserList().add(rootUser);
// 用户组对象转JSON串
String jsonString = JSON.toJSONString(group);
System.out.println("jsonString:" + jsonString);
// JSON串转用户组对象
UserGroup group2 = JSON.parseObject(jsonString, UserGroup.class);
System.out.println("group2:" + group2);
// 构建用户对象数组
User[] users = new User[2];
users[0] = guestUser;
users[1] = rootUser;
// 用户对象数组转JSON串
String jsonString2 = JSON.toJSONString(users);
System.out.println("jsonString2:" + jsonString2);
// JSON串转用户对象列表
List<User> users2 = JSON.parseArray(jsonString2, User.class);
System.out.println("users2:" + users2);
}
}