首页 > 代码库 > 数据传输:JSON-fastjson

数据传输:JSON-fastjson

fastjson 是alibaba的一个Json处理工具包。

1、使用  JSON.toJSONString   和  JSON.parseObject 

fastjson只需要掌握两个静态方法:JSON.toJSONString和JSON.parseObject 

fastjson示例:

User.java

public class User {
    
    private Long   id;
    private String name;
     
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
}

Group.java

public class Group {
    
    private Long       id;
    private String     name;
    private List<User> users = new ArrayList<User>();
    
    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public List<User> getUsers() {
        return users;
    }
    public void setUsers(List<User> users) {
        this.users = users;
    }
    
    public void addUser(User user) {
        users.add(user);
    }
}

EncodeTest.java

public class EncodeTest {
    
    public static void main(String[] args) {
        Group group = new Group();
        group.setId(0L);
        group.setName("admin");
        
        User u = new User();
        u.setId(1L);
        u.setName("wangsan");
        
        User li = new User();
        li.setId(2L);
        li.setName("lisi");
        
        group.addUser(u);
        group.addUser(li);
        
        String jsonString = JSON.toJSONString(group);
        System.out.println(jsonString);
    }
}

输出结果:{"id":0,"name":"admin","users":[{"id":1,"name":"wangsan"},{"id":2,"name":"lisi"}]}

DecodeTest.java

public class DecodeTest {
    public static void main(String[] args) {
        String jsonStr = "{‘id’:0,‘name’:‘admin’,‘users’:[{‘id’:1,‘name’:‘wangsan’},{‘id’:2,‘name’:‘lisi’}]}";
        Group group = JSON.parseObject(jsonStr, Group.class);
        System.out.println(group.getId());
        System.out.println(group.getName());
        
        System.out.println(group.getUsers().get(0).getId());
        System.out.println(group.getUsers().get(0).getName());
    }
}

2、net.sf.json.JSONException: Object is null

net.sf.json.JSONException: Object is null:

JSONArray或JSONObject转换时,对象内包含另一个对象,而该被包含的对象为NULL,抛出异常

 

 

参考资料:

1、fastjson  Github  地址 :https://github.com/alibaba/fastjson

2、JSON 之 fastjson 解析 : http://blog.sina.com.cn/s/blog_7ffb8dd501013qas.html

数据传输:JSON-fastjson