日期:2014-05-16  浏览次数:20357 次

fastJson在java后台转换json格式数据探究(二)--处理数组/List/Map

?

package fastJson.test; 
 

import java.util.ArrayList; 
import java.util.HashMap; 

import java.util.List; 
import java.util.Map; 

 
import com.alibaba.fastjson.JSON; 

import com.alibaba.fastjson.JSONArray; 
 

public class FastJsonTest1 
{ 

 
    /**

     * 数组转json格式字符串
     */ 

    public void array2Json(){ 
        String[] arr = {"bill","green","maks","jim"}; 

        String jsonText = JSON.toJSONString(arr, true); 
        System.out.println("array2Json()方法:jsonText=="+jsonText); 

        // 输出结果:jsonText==["bill","green","maks","jim"]  
    } 

 
    /**

     * json格式字符串转数组
     */ 

    public void json2Array(){ 
        String jsonText = "[\"bill\",\"green\",\"maks\",\"jim\"]"; 

        JSONArray jsonArr = JSON.parseArray(jsonText); 
        System.out.println("json2Array()方法:jsonArr=="+jsonArr); 

        // 输出结果:jsonArr==["bill","green","maks","jim"]  
    } 

     
    /**

     * 数组转json格式字符串
     */ 

    public void array2Json2(){ 
        User user1 = new User("P001","TOM",16); 

        User user2 = new User("P002","JACKSON",21); 
        User user3 = new User("P003","MARTIN",20); 

        User[] userArr = {user1,user2,user3}; 
        String jsonText = JSON.toJSONString(userArr, true); 

        System.out.println("array2Json2()方法:jsonText=="+jsonText); 
        //输出结果:jsonText==[{"age":16,"id":"P001","name":"TOM"},{"age":21,"id":"P002","name":"JACKSON"},{"age":20,"id":"P003","name":"MARTIN"}]  

    } 
     

    /**
     * json格式字符串转数组

     */ 
    public void json2Array2(){ 

        String jsonText = "[{\"age\":16,\"id\":\"P001\",\"name\":\"TOM\"},{\"age\":21,\"id\":\"P002\",\"name\":\"JACKSON\"},{\"age\":20,\"id\":\"P003\",\"name\":\"MARTIN\"}]"; 
        JSONArray jsonArr = JSON.parseArray(jsonText); 

        System.out.println("json2Array2()方法:jsonArr=="+jsonArr); 
        // 输出结果:jsonArr==[{"age":16,"id":"P001","name":"TOM"},{"age":21,"id":"P002","name":"JACKSON"},{"age":20,"id":"P003","name":"MARTIN"}]  

    } 
     

    /**
     * list集合转json格式字符串

     */ 
    public void list2Json(){ 

        List list = new ArrayList(); 
        User user1 = new User("L001","TOM",16); 

        list.add(user1); 
        User user2 = new User("L002","JACKSON",21); 

        list.add(user2); 
        User user3 = new User("L003","MARTIN",20); 

        list.add(user3); 
        String jsonText = JSON.toJSONString(list, true); 

        System.out.pri