알리바바를 사용한 FastJson의 몇 가지 예.

2763 단어
import java.util.List;
import java.util.ArrayList;
import com.alibaba.fastjson.JSON;

/**
 *  FastJson json 、 json 
 * 
 * @author higher2016
 * @2016-12-27
 */
public class FastJsonDemo {
    public static void main(String[] args) {
        
        //  geust
        User guestUser = new User();
        guestUser.setName("guest");
        guestUser.setAge(28);
        
        //  root
        User rootUser = new User();
        rootUser.setName("root");
        guestUser.setAge(35);
        
        //  
        UserGroup group = new UserGroup();
        group.setName("admin");
        group.getUsers().add(guestUser);
        group.getUsers().add(rootUser);
        
        // json 
        String jsonString = JSON.toJSONString(group);
        System.out.println("jsonString:"+jsonString);
        
        // json 
        UserGroup group1 = JSON.parseObject(jsonString, UserGroup.class);
        System.out.println(group1);
        
        // json 
        User[] users = new User[2];
        users[0] = guestUser;
        users[1] = rootUser;
        String jsonString1 = JSON.toJSONString(users);
        System.out.println("jsonString1:"+jsonString1);
        
        //json List
        List user2 = JSON.parseArray(jsonString1, User.class);
        System.out.println(user2);
    }

    class User {
        private String name;
        private int age;
        public User() {
            super();
            // TODO Auto-generated constructor stub
        }
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public int getAge() {
            return age;
        }
        public void setAge(int age) {
            this.age = age;
        }
        @Override
        public String toString(){
            return "User={ "+"name:"+this.name+", age:"+this.age+" }";
        }
    }

    class UserGroup {
        private String name;
        private List users  = new ArrayList();
        public String getName() {
            return name;
        }
        public void setName(String name) {
            this.name = name;
        }
        public List getUsers() {
            return users;
        }
        public void setUser(List users) {
            this.users = users;
        }
        public UserGroup() {
            super();
            // TODO Auto-generated constructor stub
        }
        @Override
        public String toString(){
            return "UserGroup:{ name="+this.name+", user="+this.users+" }";
        }   
    }
}

좋은 웹페이지 즐겨찾기