本文参考:http://www.tuicool.com/articles/zUbQfa
http://blog.csdn.net/glarystar/article/details/6654494
在日志解析,前后端数据传输交互中,经常会遇到 String 与 map、json、xml 等格式相互转换与解析的场景,其中 json 基本成为了跨语言、跨前后端的事实上的标准数据交互格式。应该来说各个语言中 解析 json 的库都一大片(具体 json 格式与三方库的介绍请见:http://www.json.org/json-zh.html),比如 python 都集成在了内置库中,成为标准 API,今天我们要聊的是 java 中如何方便的使用 json 格式。
从上面的链接介绍中我们可以看到,java 的三方 json 库是最多的,可谓百花齐放百家争鸣的节奏。。。但是,某些库存在链式依赖的问题,使用的时候要注意,如果你没用 maven 管你你的依赖,用起来会很痛苦,比如 json-lib、smart-json 等。下面我要推荐的是阿里巴巴工程师开源的一个 json 库:FastJSON,这个库在解析速度和易用性上来说都很不错。
1、了解fastjson
1.1 Fastjson介绍
Fastjson是一个Java语言编写的JSON处理器。
1、遵循 http://json.org 标准,为其官方网站收录的参考实现之一。
2、功能qiang打,支持JDK的各种类型,包括基本的JavaBean、Collection、Map、Date、Enum、泛型。
3、无依赖,不需要例外额外的jar,能够直接跑在JDK上。
4、开源,使用Apache License 2.0协议开源。
1、遵循 http://json.org 标准,为其官方网站收录的参考实现之一。
2、功能qiang打,支持JDK的各种类型,包括基本的JavaBean、Collection、Map、Date、Enum、泛型。
3、无依赖,不需要例外额外的jar,能够直接跑在JDK上。
4、开源,使用Apache License 2.0协议开源。
1.2 如果获得Fastjson?
https://github.com/alibaba/fastjson
https://github.com/alibaba/fastjson
2、主要的使用入口
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<Object>
JSONObject:相当于Map<String, Object>
JSON反序列化没有真正数组,本质类型都是List<Object>
4、fastjson还有很多很高级的特性
比如支持注解、支持全类型序列化,这些都是很好的特性,功能强大,不在本次测试范围。
5、测试代码
Bar.java
1 import java.util.Date; 2 import java.util.Random; 3 4 import com.alibaba.fastjson.JSON; 5 import com.alibaba.fastjson.serializer.SerializeConfig; 6 import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 7 8 /** 9 * @author leizhimin 11-11-22 上午9:15 10 */ 11 public class Bar { 12 //SerializeConfig:是对序列化过程中一些序列化过程的特殊配置,这里用作日期格式的定义。 13 public static SerializeConfig mapping = new SerializeConfig(); 14 15 private String barName; 16 private int barAge; 17 private Date barDate = new Date(); 18 19 static { 20 mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd")); 21 } 22 23 //代码块给Bar对象中的barName和barAge赋值. 24 { 25 Random random = new Random(); 26 barName = "name_"+String.valueOf(random.nextInt()); 27 barAge = random.nextInt(); 28 } 29 30 public static void main(String[] args) { 31 //把Bar对象转换成JSON格式的Object类型 32 Object obj = JSON.toJSON(new Bar()); 33 System.out.println(obj); 34 //输出{"barAge":-664880579,"barDate":1471348117095,"barName":"name_464160862"} 35 36 //Bar对象转换成String类型的字符串 37 String x1 = JSON.toJSONString(new Bar(), true); 38 System.out.println(x1); 39 //输出: 40 /* 41 { 42 "barAge":1553774697, 43 "barDate":1471348117144, 44 "barName":"name_-1034255192" 45 } 46 */ 47 48 //格式化时间的JSON字符串 49 String x2 = JSON.toJSONString(new Bar(), mapping); 50 System.out.println(x2); 51 //输出:{"barAge":1755982737,"barDate":"2016-08-16","barName":"name_453018403"} 52 } 53 54 public String getBarName() { 55 return barName; 56 } 57 58 public void setBarName(String barName) { 59 this.barName = barName; 60 } 61 62 public int getBarAge() { 63 return barAge; 64 } 65 66 public void setBarAge(int barAge) { 67 this.barAge = barAge; 68 } 69 70 public Date getBarDate() { 71 return barDate; 72 } 73 74 public void setBarDate(Date barDate) { 75 this.barDate = barDate; 76 } 77 78 @Override 79 public String toString() { 80 return "Bar{" + 81 "barName='" + barName + '\'' + 82 ", barAge=" + barAge + 83 ", barDate=" + barDate + 84 '}'; 85 } 86 }
Foo.java
1 import java.util.ArrayList; 2 import java.util.Date; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 /** 8 * @author leizhimin 11-11-22 上午9:15 9 */ 10 public class Foo { 11 //声明Java中的8种基本变量和String类型变量. 12 private String vString = "vStringhehhehe"; 13 14 private char vchar = 'x'; 15 private byte vbyte = 64; 16 private short vshort = 128; 17 private int vint = 65535; 18 private long vlong = 9999999L; 19 private float vfloat = 12.1f; 20 private double vdouble = 22.203d; 21 private boolean vboolean = false; 22 23 //Date和Object类型变量 24 private Date vDate = new Date(); 25 private Object vnull = null; 26 27 //String,int,boolean类型的数组 28 private String[] avString = {"aaa", "bbb", "ccc"}; 29 private int[] avint = {1, 2, 3, 4}; 30 private boolean[] avboolean = {true, false, true, true}; 31 32 //List和Map类型变量 33 private List<String> listString = new ArrayList<String>(); 34 private Map<String, String> map = new HashMap<String, String>(); 35 36 //封装的Bar对象 37 private Bar bar = new Bar(); 38 private Bar[] avBar = {new Bar(), new Bar()}; 39 private List<Bar> listBar = new ArrayList<Bar>(); 40 41 //代码块封装数据 42 { 43 listString.add("listString1"); 44 listString.add("listString2"); 45 listString.add("listString3"); 46 47 map.put("x", "s11111x"); 48 map.put("y", "s22222y"); 49 map.put("z", "s33333z"); 50 51 listBar.add(new Bar()); 52 listBar.add(new Bar()); 53 listBar.add(new Bar()); 54 } 55 56 public String getvString() { 57 return vString; 58 } 59 60 public void setvString(String vString) { 61 this.vString = vString; 62 } 63 64 public char getVchar() { 65 return vchar; 66 } 67 68 public void setVchar(char vchar) { 69 this.vchar = vchar; 70 } 71 72 public byte getVbyte() { 73 return vbyte; 74 } 75 76 public void setVbyte(byte vbyte) { 77 this.vbyte = vbyte; 78 } 79 80 public short getVshort() { 81 return vshort; 82 } 83 84 public void setVshort(short vshort) { 85 this.vshort = vshort; 86 } 87 88 public int getVint() { 89 return vint; 90 } 91 92 public void setVint(int vint) { 93 this.vint = vint; 94 } 95 96 public long getVlong() { 97 return vlong; 98 } 99 100 public void setVlong(long vlong) { 101 this.vlong = vlong; 102 } 103 104 public float getVfloat() { 105 return vfloat; 106 } 107 108 public void setVfloat(float vfloat) { 109 this.vfloat = vfloat; 110 } 111 112 public double getVdouble() { 113 return vdouble; 114 } 115 116 public void setVdouble(double vdouble) { 117 this.vdouble = vdouble; 118 } 119 120 public boolean isVboolean() { 121 return vboolean; 122 } 123 124 public void setVboolean(boolean vboolean) { 125 this.vboolean = vboolean; 126 } 127 128 public Date getvDate() { 129 return vDate; 130 } 131 132 public void setvDate(Date vDate) { 133 this.vDate = vDate; 134 } 135 136 public Object getVnull() { 137 return vnull; 138 } 139 140 public void setVnull(Object vnull) { 141 this.vnull = vnull; 142 } 143 144 public String[] getAvString() { 145 return avString; 146 } 147 148 public void setAvString(String[] avString) { 149 this.avString = avString; 150 } 151 152 public int[] getAvint() { 153 return avint; 154 } 155 156 public void setAvint(int[] avint) { 157 this.avint = avint; 158 } 159 160 public boolean[] getAvboolean() { 161 return avboolean; 162 } 163 164 public void setAvboolean(boolean[] avboolean) { 165 this.avboolean = avboolean; 166 } 167 168 public List<String> getListString() { 169 return listString; 170 } 171 172 public void setListString(List<String> listString) { 173 this.listString = listString; 174 } 175 176 public Map<String, String> getMap() { 177 return map; 178 } 179 180 public void setMap(Map<String, String> map) { 181 this.map = map; 182 } 183 184 public Bar getBar() { 185 return bar; 186 } 187 188 public void setBar(Bar bar) { 189 this.bar = bar; 190 } 191 192 public Bar[] getAvBar() { 193 return avBar; 194 } 195 196 public void setAvBar(Bar[] avBar) { 197 this.avBar = avBar; 198 } 199 200 public List<Bar> getListBar() { 201 return listBar; 202 } 203 204 public void setListBar(List<Bar> listBar) { 205 this.listBar = listBar; 206 } 207 }
Test.java
1 import java.util.ArrayList; 2 import java.util.Date; 3 import java.util.HashMap; 4 import java.util.List; 5 import java.util.Map; 6 7 import com.alibaba.fastjson.JSON; 8 import com.alibaba.fastjson.JSONArray; 9 import com.alibaba.fastjson.serializer.SerializeConfig; 10 import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; 11 12 /** 13 * Created by 2IntelliJ IDEA. 14 * 15 * @author leizhimin 11-11-22 上午9:45 16 */ 17 public class Test { 18 private static SerializeConfig mapping = new SerializeConfig(); 19 static { 20 mapping.put(Date.class, new SimpleDateFormatSerializer("yyyy-MM-dd HH:mm:ss")); 21 } 22 23 public static void main(String[] args) { 24 25 Date date = new Date(); 26 String text = JSON.toJSONString(date, mapping); 27 System.out.println(text);//输出"2016-08-16 19:53:07" 28 29 Foo f1 = new Foo(); 30 System.out.println(JSON.toJSONString(f1, true)); 31 32 String x2 =JSON.toJSONString(f1, mapping); 33 System.out.println(x2); 34 35 //List -> JSON array 36 json2List(); 37 38 json2Map(); 39 40 //普通类型Array数组和JSON的相互转换 41 array2JSON(); 42 43 array2JSON2(); 44 45 //普通类型Map和JSON的相互转换 46 map2JSON(); 47 } 48 49 public static void json2List(){ 50 //List -> JSON array 51 List<Bar> barList = new ArrayList<Bar>(); 52 barList.add(new Bar()); 53 barList.add(new Bar()); 54 barList.add(new Bar()); 55 String json= JSON.toJSONString(barList, true); 56 System.out.println(json); 57 58 //JSON array -> List 59 List<Bar> barList1 = JSON.parseArray(json,Bar.class); 60 for (Bar bar : barList1) { 61 System.out.println(bar.toString()); 62 } 63 } 64 65 public static void json2Map(){ 66 //Map -> JSON 67 Map<String,Bar> map = new HashMap<String, Bar>(); 68 map.put("a",new Bar()); 69 map.put("b",new Bar()); 70 map.put("c",new Bar()); 71 String json = JSON.toJSONString(map,true); 72 System.out.println(json); 73 74 //JSON -> Map 75 Map<String,Bar> map1 = (Map<String,Bar>)JSON.parse(json); 76 for (String key : map1.keySet()) { 77 System.out.println(key+":"+map1.get(key)); 78 } 79 } 80 81 82 public static void array2JSON(){ 83 //String数组转换成JSON 84 String[] arr_String = {"a","b","c"}; 85 String json_arr_String = JSON.toJSONString(arr_String,true); 86 System.out.println(json_arr_String); //输出["a","b","c"] 87 88 //JSON转换成array 89 JSONArray jsonArray = JSON.parseArray(json_arr_String); 90 for (Object o : jsonArray) { 91 System.out.println(o); 92 } 93 /* 输出: 94 a 95 b 96 c 97 */ 98 System.out.println(jsonArray);//输出:["a","b","c"] 99 } 100 101 public static void array2JSON2(){ 102 Bar[] arr_Bar = {new Bar(),new Bar(),new Bar()}; 103 String json_arr_Bar = JSON.toJSONString(arr_Bar,true); 104 System.out.println(json_arr_Bar); 105 JSONArray jsonArray = JSON.parseArray(json_arr_Bar); 106 for (Object o : jsonArray) { 107 System.out.println(o); 108 } 109 System.out.println(jsonArray); 110 } 111 112 113 public static void map2JSON(){ 114 115 //Map转换成JSON 116 Map<String,String> map = new HashMap<String,String>(); 117 map.put("a","aaa"); 118 map.put("b","bbb"); 119 map.put("c","ccc"); 120 String json=JSON.toJSONString(map); 121 System.out.println(json);//输出{"a":"aaa","b":"bbb","c":"ccc"} 122 123 //JSON转换成Map 124 Map map1 = JSON.parseObject(json); 125 for (Object o : map.entrySet()) { 126 Map.Entry<String,String> entry = (Map.Entry<String,String>)o; 127 System.out.println(entry.getKey()+"--->"+entry.getValue()); 128 } 129 /* 130 b--->bbb 131 c--->ccc 132 a--->aaa 133 */ 134 } 135 }
程序输出:
1 "System.out.println(text);" 2 "2016-08-17 10:16:18" 3 4 System.out.println(JSON.toJSONString(f1, true)); 5 { 6 "avBar":[{ 7 "barAge":-480029500, 8 "barDate":1471400178210, 9 "barName":"name_-2129248362" 10 },{ 11 "barAge":634833464, 12 "barDate":1471400178210, 13 "barName":"name_-1877607258" 14 }], 15 "avString":["aaa","bbb","ccc"], 16 "avboolean":[true,false,true,true], 17 "avint":[1,2,3,4], 18 "bar":{ 19 "barAge":-1335514550, 20 "barDate":1471400178210, 21 "barName":"name_-1069927371" 22 }, 23 "listBar":[ 24 { 25 "barAge":357976541, 26 "barDate":1471400178210, 27 "barName":"name_1051748274" 28 }, 29 { 30 "barAge":1253923759, 31 "barDate":1471400178210, 32 "barName":"name_1279150198" 33 }, 34 { 35 "barAge":357167456, 36 "barDate":1471400178210, 37 "barName":"name_-737334111" 38 } 39 ], 40 "listString":[ 41 "listString1", 42 "listString2", 43 "listString3" 44 ], 45 "map":{ 46 "x":"s11111x", 47 "y":"s22222y", 48 "z":"s33333z" 49 }, 50 "vDate":1471400178209, 51 "vString":"vStringhehhehe", 52 "vboolean":false, 53 "vbyte":64, 54 "vchar":"x", 55 "vdouble":22.203, 56 "vfloat":12.1, 57 "vint":65535, 58 "vlong":9999999, 59 "vshort":128 60 } 61 System.out.println(x2); 62 {"avBar":[{"barAge":-480029500,"barDate":"2016-08-17 10:16:18","barName":"name_-2129248362"},{"barAge":634833464,"barDate":"2016-08-17 10:16:18","barName":"name_-1877607258"}],"avString":["aaa","bbb","ccc"],"avboolean":[true,false,true,true],"avint":[1,2,3,4],"bar":{"barAge":-1335514550,"barDate":"2016-08-17 10:16:18","barName":"name_-1069927371"},"listBar":[{"barAge":357976541,"barDate":"2016-08-17 10:16:18","barName":"name_1051748274"},{"barAge":1253923759,"barDate":"2016-08-17 10:16:18","barName":"name_1279150198"},{"barAge":357167456,"barDate":"2016-08-17 10:16:18","barName":"name_-737334111"}],"listString":["listString1","listString2","listString3"],"map":{"x":"s11111x","y":"s22222y","z":"s33333z"},"vDate":"2016-08-17 10:16:18","vString":"vStringhehhehe","vboolean":false,"vbyte":64,"vchar":"x","vdouble":22.203,"vfloat":12.1,"vint":65535,"vlong":9999999,"vshort":128} 63 64 json2List(); 65 [ 66 { 67 "barAge":-2022440599, 68 "barDate":1471400178284, 69 "barName":"name_-590972614" 70 }, 71 { 72 "barAge":1704306424, 73 "barDate":1471400178284, 74 "barName":"name_1482085108" 75 }, 76 { 77 "barAge":1907038490, 78 "barDate":1471400178284, 79 "barName":"name_651427557" 80 } 81 ] 82 83 Bar{barName='name_-590972614', barAge=-2022440599, barDate=Wed Aug 17 10:16:18 CST 2016} 84 Bar{barName='name_1482085108', barAge=1704306424, barDate=Wed Aug 17 10:16:18 CST 2016} 85 Bar{barName='name_651427557', barAge=1907038490, barDate=Wed Aug 17 10:16:18 CST 2016} 86 87 json2Map(); 88 { 89 "a":{ 90 "barAge":877829686, 91 "barDate":1471400178308, 92 "barName":"name_558391664" 93 }, 94 "b":{ 95 "barAge":375478040, 96 "barDate":1471400178308, 97 "barName":"name_-1233383964" 98 }, 99 "c":{ 100 "barAge":-1043862971, 101 "barDate":1471400178308, 102 "barName":"name_-823025454" 103 } 104 } 105 106 b:{"barAge":375478040,"barDate":1471400178308,"barName":"name_-1233383964"} 107 c:{"barAge":-1043862971,"barDate":1471400178308,"barName":"name_-823025454"} 108 a:{"barAge":877829686,"barDate":1471400178308,"barName":"name_558391664"} 109 110 array2JSON() 111 ["a","b","c"] 112 a 113 b 114 c 115 ["a","b","c"] 116 117 array2JSON2() 118 [{ 119 "barAge":-842219577, 120 "barDate":1471400178310, 121 "barName":"name_-1204063138" 122 },{ 123 "barAge":1450191787, 124 "barDate":1471400178310, 125 "barName":"name_650041812" 126 },{ 127 "barAge":-732707567, 128 "barDate":1471400178310, 129 "barName":"name_159117539" 130 }] 131 132 {"barAge":-842219577,"barDate":1471400178310,"barName":"name_-1204063138"} 133 {"barAge":1450191787,"barDate":1471400178310,"barName":"name_650041812"} 134 {"barAge":-732707567,"barDate":1471400178310,"barName":"name_159117539"} 135 [{"barAge":-842219577,"barDate":1471400178310,"barName":"name_-1204063138"},{"barAge":1450191787,"barDate":1471400178310,"barName":"name_650041812"},{"barAge":-732707567,"barDate":1471400178310,"barName":"name_159117539"}] 136 137 map2JSON() 138 {"a":"aaa","b":"bbb","c":"ccc"} 139 b--->bbb 140 c--->ccc 141 a--->aaa