Fastjson使用

fastjson主要的使 用入口

Fastjson API入口类是com.alibaba.fastjson.JSON,常用的序列化操作都可以在JSON类上的静态方法直接完成。

  1. public static final Object parse(String text); // 把JSON文本parse为JSONObject或者JSONArray
  2. public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject
  3. public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse为JavaBean
  4. public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray
  5. public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合
  6. public static final String toJSONString(Object object); // 将JavaBean序列化为JSON文本
  7. public static final String toJSONString(Object object, boolean prettyFormat); // 将JavaBean序列化为带格式的JSON文本
  8. public static final Object toJSON(Object javaObject); JavaBean转换为JSONObject或者JSONArray

3、有关类库的一些说明

SerializeWriter:相当于StringBuffer

JSONArray:相当于List

JSONObject:相当于Map

JSON反序列化没有真正数组,本质类型都是List

4、fastjson还有很多很高级的特性

比如支持注解、支持全类型序列化,这些都是很好的特性,功能强大,不在本次测试范围。

5、测试代码

  1. package lavasoft.stu.json;
  2. import com.alibaba.fastjson.JSON;
  3. import com.alibaba.fastjson.serializer.SerializeConfig;
  4. import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer;
  5. import java.util.*;
  6. /**
  7. * Created by IntelliJ IDEA.
  8. *
  9. * @author leizhimin 11-11-22 上午9:15
  10. */
  11. public class Foo {
  12. private String vString = "vStringhehhehe";
  13. private char vchar = 'x';
  14. private byte vbyte = 64;
  15. private short vshort = 128;
  16. private int vint = 65535;
  17. private long vlong = 9999999L;
  18. private float vfloat = 12.1f;
  19. private double vdouble = 22.203d;
  20. private boolean vboolean = false;
  21. // private Date vdate = new Date();
  22. private Date dddd = new Date();
  23. private Date vDate = new Date();
  24. private Date v_Date = new Date();
  25. private Object vnull = null;
  26. private String[] avString = {"aaa", "bbb", "ccc"};
  27. private int[] avint = {1, 2, 3, 4};
  28. private boolean[] avboolean = {true, false, true, true};
  29. private List<String> listString = new ArrayList<String>();
  30. private Map<String, String> map = new HashMap<String, String>();
  31. private Bar bar = new Bar();
  32. private Bar[] avBar = {new Bar(), new Bar()};
  33. private List<Bar> listBar = new ArrayList<Bar>();
  34. {
  35. listString.add("listString1");
  36. listString.add("listString2");
  37. listString.add("listString3");
  38. map.put("x", "s11111x");
  39. map.put("y", "s22222y");
  40. map.put("z", "s33333z");
  41. listBar.add(new Bar());
  42. listBar.add(new Bar());
  43. listBar.add(new Bar());
  44. }
  45. public String getvString() {
  46. return vString;
  47. }
  48. public void setvString(String vString) {
  49. this.vString = vString;
  50. }
  51. public char getVchar() {
  52. return vchar;
  53. }
  54. public void setVchar(char vchar) {
  55. this.vchar = vchar;
  56. }
  57. public byte getVbyte() {
  58. return vbyte;
  59. }
  60. public void setVbyte(byte vbyte) {
  61. this.vbyte = vbyte;
  62. }
  63. public short getVshort() {
  64. return vshort;
  65. }
  66. public void setVshort(short vshort) {
  67. this.vshort = vshort;
  68. }
  69. public int getVint() {
  70. return vint;
  71. }
  72. public void setVint(int vint) {
  73. this.vint = vint;
  74. }
  75. public long getVlong() {
  76. return vlong;
  77. }
  78. public void setVlong(long vlong) {
  79. this.vlong = vlong;
  80. }
  81. public float getVfloat() {
  82. return vfloat;
  83. }
  84. public void setVfloat(float vfloat) {
  85. this.vfloat = vfloat;
  86. }
  87. public double getVdouble() {
  88. return vdouble;
  89. }
  90. public void setVdouble(double vdouble) {
  91. this.vdouble = vdouble;
  92. }
  93. public boolean isVboolean() {
  94. return vboolean;
  95. }
  96. public void setVboolean(boolean vboolean) {
  97. this.vboolean = vboolean;
  98. }
  99. public Date getDddd() {
  100. return dddd;
  101. }
  102. public void setDddd(Date dddd) {
  103. this.dddd = dddd;
  104. }
  105. public Date getV_Date() {
  106. return v_Date;
  107. }
  108. public void setV_Date(Date v_Date) {
  109. this.v_Date = v_Date;
  110. }
  111. public Date getvDate() {
  112. return vDate;
  113. }
  114. public void setvDate(Date vDate) {
  115. this.vDate = vDate;
  116. }
  117. public Object getVnull() {
  118. return vnull;
  119. }
  120. public void setVnull(Object vnull) {
  121. this.vnull = vnull;
  122. }
  123. public String[] getAvString() {
  124. return avString;
  125. }
  126. public void setAvString(String[] avString) {
  127. this.avString = avString;
  128. }
  129. public int[] getAvint() {
  130. return avint;
  131. }
  132. public void setAvint(int[] avint) {
  133. this.avint = avint;
  134. }
  135. public boolean[] getAvboolean() {
  136. return avboolean;
  137. }
  138. public void setAvboolean(boolean[] avboolean) {
  139. this.avboolean = avboolean;
  140. }
  141. public List<String> getListString() {
  142. return listString;
  143. }
  144. public void setListString(List<String> listString) {
  145. this.listString = listString;
  146. }
  147. public Map<String, String> getMap() {
  148. return map;
  149. }
  150. public void setMap(Map<String, String> map) {
  151. this.map = map;
  152. }
  153. public Bar getBar() {
  154. return bar;
  155. }
  156. public void setBar(Bar bar) {
  157. this.bar = bar;
  158. }
  159. public Bar[] getAvBar() {
  160. return avBar;
  161. }
  162. public void setAvBar(Bar[] avBar) {
  163. this.avBar = avBar;
  164. }
  165. public List<Bar> getListBar() {
  166. return listBar;
  167. }
  168. public void setListBar(List<Bar> listBar) {
  169. this.listBar = listBar;
  170. }
  171. }
package lavasoft.stu.json; 

import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.serializer.SerializeConfig; 
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 

import java.util.Date; 
import java.util.Random; 

/** 
* Created by IntelliJ IDEA. 
* 
* @author leizhimin 11-11-22 上午9:15 
*/ 
public class Bar { 
    public static SerializeConfig mapping = new SerializeConfig(); 
    private String barName; 
    private int barAge; 
    private Date barDate = new Date(); 
    static { 
        mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); 
    } 
    { 
        Random r = new Random(); 
        barName = "sss_"+String.valueOf(r.nextFloat()); 
        barAge = r.nextInt(); 
    } 

    public static void main(String[] args) { 
        Object obj = JSON.toJSON(new Bar()); 
        String x1 = JSON.toJSONString(new Bar(), true); 
        System.out.println(x1); 
        String x2 = JSON.toJSONString(new Bar(), mapping); 
        System.out.println(x2); 
    } 

    public String getBarName() { 
        return barName; 
    } 

    public void setBarName(String barName) { 
        this.barName = barName; 
    } 

    public int getBarAge() { 
        return barAge; 
    } 

    public void setBarAge(int barAge) { 
        this.barAge = barAge; 
    } 

    public Date getBarDate() { 
        return barDate; 
    } 

    public void setBarDate(Date barDate) { 
        this.barDate = barDate; 
    } 

    @Override 
    public String toString() { 
        return "Bar{" + 
                "barName='" + barName + '\'' + 
                ", barAge=" + barAge + 
                ", barDate=" + barDate + 
                '}'; 
    } 
}
package lavasoft.stu.json; 

import com.alibaba.fastjson.JSON; 
import com.alibaba.fastjson.JSONArray; 
import com.alibaba.fastjson.serializer.SerializeConfig; 
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 

import java.util.*; 

/** 
* Created by 2IntelliJ IDEA. 
* 
* @author leizhimin 11-11-22 上午9:45 
*/ 
public class Test { 
    private static SerializeConfig mapping = new SerializeConfig(); static { 
        mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 
    } 

    public static void main(String[] args) { 
        Foo f1 = new Foo(); 
        Date date = new Date(); 
        String text = JSON.toJSONString(date, mapping); 
        System.out.println(text); 
        System.out.println(JSON.toJSONString(f1, true)); 
        String x2 =JSON.toJSONString(f1, mapping); 
        System.out.println(x2); 
    } 

    public static void json2List(){ 
        //List -> JSON array 
        List<Bar> barList = new ArrayList<Bar>(); 
        barList.add(new Bar()); 
        barList.add(new Bar()); 
        barList.add(new Bar()); 
        String json= JSON.toJSONString(barList, true); 
        System.out.println(json); 
        //JSON array -> List 
        List<Bar> barList1 = JSON.parseArray(json,Bar.class); 
        for (Bar bar : barList1) { 
            System.out.println(bar.toString()); 
        } 
    } 

    public static void json2Map(){ 
        //Map -> JSON 
        Map<String,Bar> map = new HashMap<String, Bar>(); 
        map.put("a",new Bar()); 
        map.put("b",new Bar()); 
        map.put("c",new Bar()); 
        String json = JSON.toJSONString(map,true); 
        System.out.println(json); 
        //JSON -> Map 
        Map<String,Bar> map1 = (Map<String,Bar>)JSON.parse(json); 
        for (String key : map1.keySet()) { 
            System.out.println(key+":"+map1.get(key)); 
        } 
    } 

    public static void array2JSON(){ 
        String[] arr_String    = {"a","b","c"}; 
        String json_arr_String = JSON.toJSONString(arr_String,true); 
        System.out.println(json_arr_String); 
        JSONArray jsonArray = JSON.parseArray(json_arr_String); 
        for (Object o : jsonArray) { 
            System.out.println(o); 
        } 
        System.out.println(jsonArray); 
    } 
    public static void array2JSON2(){ 
        Bar[] arr_Bar    = {new Bar(),new Bar(),new Bar()}; 
        String json_arr_Bar = JSON.toJSONString(arr_Bar,true); 
        System.out.println(json_arr_Bar); 
        JSONArray jsonArray = JSON.parseArray(json_arr_Bar); 
        for (Object o : jsonArray) { 
            System.out.println(o); 
        } 
        System.out.println(jsonArray); 
    } 

    public static void map2JSON(){ 
        Map map = new HashMap(); 
        map.put("a","aaa"); 
        map.put("b","bbb"); 
        map.put("c","ccc"); 
        String json=JSON.toJSONString(map); 
        System.out.println(json); 
        Map map1 = JSON.parseObject(json); 
        for (Object o : map.entrySet()) { 
            Map.Entry<String,String> entry = (Map.Entry<String,String>)o; 
            System.out.println(entry.getKey()+"--->"+entry.getValue()); 
        } 
    } 
}

说明:

SerializeConfig:是对序列化过程中一些序列化过程的特殊配置,这里用作日期格式的定义。

有关需要带类型的全类型序列化过程,需要调用JSON.toJSONStringZ()方法。

需要美化输出时候,需要打开序列化美化开关,在方法中true那个参数。

输出结果:

"2011-11-23 23:30:33" 
{ 
  "avBar":[{ 
    "barAge":174398800, 
    "barDate":1322062233062, 
    "barName":"sss_0.62378174" 
  },{ 
    "barAge":38938962, 
    "barDate":1322062233062, 
    "barName":"sss_0.36014742" 
  }], 
  "avString":["aaa","bbb","ccc"], 
  "avboolean":[true,false,true,true], 
  "avint":[1,2,3,4], 
  "bar":{ 
    "barAge":1601495948, 
    "barDate":1322062233062, 
    "barName":"sss_0.46644872" 
  }, 
  "dddd":1322062233046, 
  "listBar":[ 
    { 
      "barAge":-1090113522, 
      "barDate":1322062233062, 
      "barName":"sss_0.83562374" 
    }, 
    { 
      "barAge":478603194, 
      "barDate":1322062233062, 
      "barName":"sss_0.59483266" 
    }, 
    { 
      "barAge":1118357669, 
      "barDate":1322062233062, 
      "barName":"sss_0.9961642" 
    } 
  ], 
  "listString":[ 
    "listString1", 
    "listString2", 
    "listString3" 
  ], 
  "map":{"x":"s11111x","y":"s22222y","z":"s33333z"}, 
  "v_Date":1322062233046, 
  "vboolean":false, 
  "vbyte":64, 
  "vchar":"x", 
  "vdouble":22.203, 
  "vfloat":12.1, 
  "vint":65535, 
  "vlong":9999999, 
  "vshort":128 
} 
{"avBar":[{"barAge":174398800,"barDate":"2011-11-23 23:30:33","barName":"sss_0.62378174"},{"barAge":38938962,"barDate":"2011-11-23 23:30:33","barName":"sss_0.36014742"}],"avString":["aaa","bbb","ccc"],"avboolean":[true,false,true,true],"avint":[1,2,3,4],"bar":{"barAge":1601495948,"barDate":"2011-11-23 23:30:33","barName":"sss_0.46644872"},"dddd":"2011-11-23 23:30:33","listBar":[{"barAge":-1090113522,"barDate":"2011-11-23 23:30:33","barName":"sss_0.83562374"},{"barAge":478603194,"barDate":"2011-11-23 23:30:33","barName":"sss_0.59483266"},{"barAge":1118357669,"barDate":"2011-11-23 23:30:33","barName":"sss_0.9961642"}],"listString":["listString1","listString2","listString3"],"map":{"x":"s11111x","y":"s22222y","z":"s33333z"},"v_Date":"2011-11-23 23:30:33","vboolean":false,"vbyte":64,"vchar":"x","vdouble":22.203,"vfloat":12.1,"vint":65535,"vlong":9999999,"vshort":128} 

Process finished with exit code 0

测试小例子:

JSONObject json = new JSONObject();
json.put("aa", "11");
json.put("bb", "22");
json.put("cc", "33");
String jsonStr = json.toString();
System.out.println(jsonStr);
// {"aa":"11","bb":"22","cc":"33"}    

System.out.println(JSONObject.parseObject(jsonStr).get("aa"));
// 11

String o = "{'area':{'area':'1','pagetype':'home'},'pagetype':'home'}";
System.out.println(((Map) JSONObject.parseObject(o).get("area")).get("area"));
// 1
String text = JSON.toJSONString(o);
Map<String, Object> userMap = 
        JSON.parseObject(o, new TypeReference<Map<String, Object>>() {});
System.out.println(((Map) userMap.get("area")).get("NotExsit"));
// null

System.out.println(JSON.toJSONString((Map) userMap.get("area")));
// {"area":"1","pagetype":"home"}