其开源的下载网址为:https://github.com/AlibabaTech/fastjson。
示例代码如下:
- packagetest;
- importjava.util.ArrayList;
- importjava.util.List;
- importcom.alibaba.fastjson.JSON;
- classUser{
- privateStringname;
- privateintage;
- publicStringgetName(){
- returnname;
- }
- publicvoidsetName(Stringname){
- this.name=name;
- publicintgetAge(){
- returnage;
- publicvoidsetAge(intage){
- this.age=age;
- @Override
- publicStringtoString(){
- return"User[name="+name+",age="+age+"]";
- }
- };
- classUserGroup{
- privateList<User>users=newArrayList<User>();
- publicList<User>getUsers(){
- returnusers;
- publicvoidsetUsers(List<User>users){
- this.users=users;
- return"UserGroup[name="+name+",users="+users+"]";
- classFastJsonTest{
- publicstaticvoidmain(String[]args){
- //构建用户geust
- UserguestUser=newUser();
- guestUser.setName("guest");
- guestUser.setAge(28);
- //构建用户root
- UserrootUser=newUser();
- rootUser.setName("root");
- guestUser.setAge(35);
- //构建用户组对象
- UserGroupgroup=newUserGroup();
- group.setName("admin");
- group.getUsers().add(guestUser);
- group.getUsers().add(rootUser);
- //用户组对象转JSON串
- StringjsonString=JSON.toJSONString(group);
- System.out.println("jsonString:"+jsonString);
- //JSON串转用户组对象
- UserGroupgroup2=JSON.parSEObject(jsonString,UserGroup.class);
- System.out.println("group2:"+group2);
- //构建用户对象数组
- User[]users=newUser[2];
- users[0]=guestUser;
- users[1]=rootUser;
- //用户对象数组转JSON串
- StringjsonString2=JSON.toJSONString(users);
- System.out.println("jsonString2:"+jsonString2);
- //JSON串转用户对象列表
- List<User>users2=JSON.parseArray(jsonString2,User.class);
- System.out.println("users2:"+users2);
- }
输出如下:
- jsonString:{"name":"admin","users":[{"age":35,"name":"guest"},{"age":0,"name":"root"}]}
- group2:UserGroup[name=admin,users=[User[name=guest,age=35],User[name=root,age=0]]]
- jsonString2:[{"age":35,"name":"root"}]
- users2:[User[name=guest,age=0]]