FastJSON 簡介及其Map/JSON/String 互轉

在日誌解析,先後端數據傳輸交互中,常常會遇到 String 與 map、json、xml 等格式相互轉換與解析的場景,其中 json 基本成爲了跨語言、跨先後端的事實上的標準數據交互格式。應該來講各個語言中 解析 json 的庫都一大片(具體 json 格式與三方庫的介紹請見:http://www.json.org/json-zh.html),好比 python 都集成在了內置庫中,成爲標準 API,今天咱們要聊的是 java 中如何方便的使用 json 格式。php

從上面的連接介紹中咱們能夠看到,java 的三方 json 庫是最多的,可謂百花齊放百家爭鳴的節奏。。。可是,某些庫存在鏈式依賴的問題,使用的時候要注意,若是你沒用 maven 管你你的依賴,用起來會很痛苦,好比 json-lib、smart-json 等。下面我要推薦的是阿里巴巴工程師開源的一個 json 庫:FastJSON,這個庫在解析速度和易用性上來講都很不錯。 html

 

一、瞭解fastjson

1.1 Fastjson介紹java

Fastjson是一個Java語言編寫的JSON處理器。 
一、遵循 http://json.org 標準,爲其官方網站收錄的參考實現之一。 
二、功能qiang打,支持JDK的各類類型,包括基本的JavaBean、Collection、Map、Date、Enum、泛型。 
三、無依賴,不須要例外額外的jar,可以直接跑在JDK上。 
四、開源,使用Apache License 2.0協議開源。python

1.2 若是得到Fastjson? 
https://github.com/alibaba/fastjsongit

二、主要的使用入口

Fastjson API入口類是com.alibaba.fastjson.JSON,經常使用的序列化操做均可以在JSON類上的靜態方法直接完成。程序員

 

public static final Object parse(String text); // 把JSON文本parse爲JSONObject或者JSONArray 
public static final JSONObject parseObject(String text); // 把JSON文本parse成JSONObject    
public static final <T> T parseObject(String text, Class<T> clazz); // 把JSON文本parse爲JavaBean 
public static final JSONArray parseArray(String text); // 把JSON文本parse成JSONArray 
public static final <T> List<T> parseArray(String text, Class<T> clazz); //把JSON文本parse成JavaBean集合 
public static final String toJSONString(Object object); // 將JavaBean序列化爲JSON文本 
public static final String toJSONString(Object object, boolean prettyFormat); // 將JavaBean序列化爲帶格式的JSON文本 
public static final Object toJSON(Object javaObject); 將JavaBean轉換爲JSONObject或者JSONArray。

三、有關類庫的一些說明

SerializeWriter:至關於StringBuffergithub

JSONArray:至關於List<Object>json

JSONObject:至關於Map<String, Object>後端

JSON反序列化沒有真正數組,本質類型都是List<Object>數組

四、fastjson還有不少很高級的特性

好比支持註解、支持全類型序列化,這些都是很好的特性,功能強大,不在本次測試範圍。

五、測試代碼

 

package lavasoft.stu.json; 

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

import java.util.*; 

/** 
* Created by IntelliJ IDEA. 
* 
* @author leizhimin 11-11-22 上午9:15 
*/ 
public class Foo { 
        private String vString = "vStringhehhehe"; 
        private char vchar = 'x'; 

        private byte vbyte = 64; 
        private short vshort = 128; 
        private int vint = 65535; 
        private long vlong = 9999999L; 

        private float vfloat = 12.1f; 
        private double vdouble = 22.203d; 

        private boolean vboolean = false; 

//        private Date vdate = new Date(); 
        private Date dddd = new Date(); 
        private Date vDate = new Date(); 
        private Date v_Date = new Date(); 
        private Object vnull = null; 

        private String[] avString = {"aaa", "bbb", "ccc"}; 
        private int[] avint = {1, 2, 3, 4}; 
        private boolean[] avboolean = {true, false, true, true}; 

        private List<String> listString = new ArrayList<String>(); 
        private Map<String, String> map = new HashMap<String, String>(); 

        private Bar bar = new Bar(); 
        private Bar[] avBar = {new Bar(), new Bar()}; 
        private List<Bar> listBar = new ArrayList<Bar>(); 

        { 
                listString.add("listString1"); 
                listString.add("listString2"); 
                listString.add("listString3"); 

                map.put("x", "s11111x"); 
                map.put("y", "s22222y"); 
                map.put("z", "s33333z"); 

                listBar.add(new Bar()); 
                listBar.add(new Bar()); 
                listBar.add(new Bar()); 
        } 



        public String getvString() { 
                return vString; 
        } 

        public void setvString(String vString) { 
                this.vString = vString; 
        } 

        public char getVchar() { 
                return vchar; 
        } 

        public void setVchar(char vchar) { 
                this.vchar = vchar; 
        } 

        public byte getVbyte() { 
                return vbyte; 
        } 

        public void setVbyte(byte vbyte) { 
                this.vbyte = vbyte; 
        } 

        public short getVshort() { 
                return vshort; 
        } 

        public void setVshort(short vshort) { 
                this.vshort = vshort; 
        } 

        public int getVint() { 
                return vint; 
        } 

        public void setVint(int vint) { 
                this.vint = vint; 
        } 

        public long getVlong() { 
                return vlong; 
        } 

        public void setVlong(long vlong) { 
                this.vlong = vlong; 
        } 

        public float getVfloat() { 
                return vfloat; 
        } 

        public void setVfloat(float vfloat) { 
                this.vfloat = vfloat; 
        } 

        public double getVdouble() { 
                return vdouble; 
        } 

        public void setVdouble(double vdouble) { 
                this.vdouble = vdouble; 
        } 

        public boolean isVboolean() { 
                return vboolean; 
        } 

        public void setVboolean(boolean vboolean) { 
                this.vboolean = vboolean; 
        } 

        public Date getDddd() { 
                return dddd; 
        } 

        public void setDddd(Date dddd) { 
                this.dddd = dddd; 
        } 

        public Date getV_Date() { 
                return v_Date; 
        } 

        public void setV_Date(Date v_Date) { 
                this.v_Date = v_Date; 
        } 

        public Date getvDate() { 
                return vDate; 
        } 

        public void setvDate(Date vDate) { 
                this.vDate = vDate; 
        } 

        public Object getVnull() { 
                return vnull; 
        } 

        public void setVnull(Object vnull) { 
                this.vnull = vnull; 
        } 

        public String[] getAvString() { 
                return avString; 
        } 

        public void setAvString(String[] avString) { 
                this.avString = avString; 
        } 

        public int[] getAvint() { 
                return avint; 
        } 

        public void setAvint(int[] avint) { 
                this.avint = avint; 
        } 

        public boolean[] getAvboolean() { 
                return avboolean; 
        } 

        public void setAvboolean(boolean[] avboolean) { 
                this.avboolean = avboolean; 
        } 

        public List<String> getListString() { 
                return listString; 
        } 

        public void setListString(List<String> listString) { 
                this.listString = listString; 
        } 

        public Map<String, String> getMap() { 
                return map; 
        } 

        public void setMap(Map<String, String> map) { 
                this.map = map; 
        } 

        public Bar getBar() { 
                return bar; 
        } 

        public void setBar(Bar bar) { 
                this.bar = bar; 
        } 

        public Bar[] getAvBar() { 
                return avBar; 
        } 

        public void setAvBar(Bar[] avBar) { 
                this.avBar = avBar; 
        } 

        public List<Bar> getListBar() { 
                return listBar; 
        } 

        public void setListBar(List<Bar> listBar) { 
                this.listBar = listBar; 
        } 
}
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"}

fastjson經過各方面測試都很好,功能性能都是No.1,喜歡,它的源代碼質量很高,做者也煞費苦心,將性能作到了最好,全免超越其餘的json類庫。

從其中的源代碼中,能夠學到不少東西,在閱讀源碼後,不得不佩服做者高超的程序設計水平,和高質量的編碼。

六、Refer:

6.1 FastJSON應用前測試

http://lavasoft.blog.51cto.com/62575/723192

6.2 alibaba fastjson(json序列化器)序列化部分源碼解析-1-整體分析

http://www.iflym.com/index.php/code/alibaba-fastjson-json-serializer-chapter-source-analyse-one-global-analyse.html

6.3 FastJson---高性能JSON開發包

http://blog.csdn.net/glarystar/article/details/6654494

6.4 Creating & Parsing JSON Data With Java Servlet/Struts/JSP

http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/

6.5 作一個懶惰高效的Android程序員(3)

在org.json包和它的類可用的狀況下咱們爲何要使用這些JSON解析類庫呢?

http://blog.jobbole.com/65181/

相關文章
相關標籤/搜索