本文参考: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类上的静态方法直接完成。
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。
3、有关类库的一些说明
SerializeWriter:相当于StringBuffer
JSONArray:相当于List<Object>
JSONObject:相当于Map<String, Object>
JSON反序列化没有真正数组,本质类型都是List<Object>
4、fastjson还有很多很高级的特性
比如支持注解、支持全类型序列化,这些都是很好的特性,功能强大,不在本次测试范围。
5、测试代码
Bar.java
import java.util.Date;
import java.util.Random; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; /**
* @author leizhimin 11-11-22 上午9:15
*/
public class Bar {
//SerializeConfig:是对序列化过程中一些序列化过程的特殊配置,这里用作日期格式的定义。
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"));
} //代码块给Bar对象中的barName和barAge赋值.
{
Random random = new Random();
barName = "name_"+String.valueOf(random.nextInt());
barAge = random.nextInt();
} public static void main(String[] args) {
//把Bar对象转换成JSON格式的Object类型
Object obj = JSON.toJSON(new Bar());
System.out.println(obj);
//输出{"barAge":-664880579,"barDate":1471348117095,"barName":"name_464160862"} //Bar对象转换成String类型的字符串
String x1 = JSON.toJSONString(new Bar(), true);
System.out.println(x1);
//输出:
/*
{
"barAge":1553774697,
"barDate":1471348117144,
"barName":"name_-1034255192"
}
*/ //格式化时间的JSON字符串
String x2 = JSON.toJSONString(new Bar(), mapping);
System.out.println(x2);
//输出:{"barAge":1755982737,"barDate":"2016-08-16","barName":"name_453018403"}
} 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 +
'}';
}
}
Foo.java
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; /**
* @author leizhimin 11-11-22 上午9:15
*/
public class Foo {
//声明Java中的8种基本变量和String类型变量.
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; //Date和Object类型变量
private Date vDate = new Date();
private Object vnull = null; //String,int,boolean类型的数组
private String[] avString = {"aaa", "bbb", "ccc"};
private int[] avint = {1, 2, 3, 4};
private boolean[] avboolean = {true, false, true, true}; //List和Map类型变量
private List<String> listString = new ArrayList<String>();
private Map<String, String> map = new HashMap<String, String>(); //封装的Bar对象
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 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;
}
}
Test.java
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.SimpleDateFormatSerializer; /**
* 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) { Date date = new Date();
String text = JSON.toJSONString(date, mapping);
System.out.println(text);//输出"2016-08-16 19:53:07" Foo f1 = new Foo();
System.out.println(JSON.toJSONString(f1, true)); String x2 =JSON.toJSONString(f1, mapping);
System.out.println(x2); //List -> JSON array
json2List(); json2Map(); //普通类型Array数组和JSON的相互转换
array2JSON(); array2JSON2(); //普通类型Map和JSON的相互转换
map2JSON();
} 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数组转换成JSON
String[] arr_String = {"a","b","c"};
String json_arr_String = JSON.toJSONString(arr_String,true);
System.out.println(json_arr_String); //输出["a","b","c"] //JSON转换成array
JSONArray jsonArray = JSON.parseArray(json_arr_String);
for (Object o : jsonArray) {
System.out.println(o);
}
/* 输出:
a
b
c
*/
System.out.println(jsonArray);//输出:["a","b","c"]
} 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转换成JSON
Map<String,String> map = new HashMap<String,String>();
map.put("a","aaa");
map.put("b","bbb");
map.put("c","ccc");
String json=JSON.toJSONString(map);
System.out.println(json);//输出{"a":"aaa","b":"bbb","c":"ccc"} //JSON转换成Map
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());
}
/*
b--->bbb
c--->ccc
a--->aaa
*/
}
}
程序输出:
"System.out.println(text);"
"2016-08-17 10:16:18" System.out.println(JSON.toJSONString(f1, true));
{
"avBar":[{
"barAge":-480029500,
"barDate":1471400178210,
"barName":"name_-2129248362"
},{
"barAge":634833464,
"barDate":1471400178210,
"barName":"name_-1877607258"
}],
"avString":["aaa","bbb","ccc"],
"avboolean":[true,false,true,true],
"avint":[1,2,3,4],
"bar":{
"barAge":-1335514550,
"barDate":1471400178210,
"barName":"name_-1069927371"
},
"listBar":[
{
"barAge":357976541,
"barDate":1471400178210,
"barName":"name_1051748274"
},
{
"barAge":1253923759,
"barDate":1471400178210,
"barName":"name_1279150198"
},
{
"barAge":357167456,
"barDate":1471400178210,
"barName":"name_-737334111"
}
],
"listString":[
"listString1",
"listString2",
"listString3"
],
"map":{
"x":"s11111x",
"y":"s22222y",
"z":"s33333z"
},
"vDate":1471400178209,
"vString":"vStringhehhehe",
"vboolean":false,
"vbyte":64,
"vchar":"x",
"vdouble":22.203,
"vfloat":12.1,
"vint":65535,
"vlong":9999999,
"vshort":128
}
System.out.println(x2);
{"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} json2List();
[
{
"barAge":-2022440599,
"barDate":1471400178284,
"barName":"name_-590972614"
},
{
"barAge":1704306424,
"barDate":1471400178284,
"barName":"name_1482085108"
},
{
"barAge":1907038490,
"barDate":1471400178284,
"barName":"name_651427557"
}
] Bar{barName='name_-590972614', barAge=-2022440599, barDate=Wed Aug 17 10:16:18 CST 2016}
Bar{barName='name_1482085108', barAge=1704306424, barDate=Wed Aug 17 10:16:18 CST 2016}
Bar{barName='name_651427557', barAge=1907038490, barDate=Wed Aug 17 10:16:18 CST 2016} json2Map();
{
"a":{
"barAge":877829686,
"barDate":1471400178308,
"barName":"name_558391664"
},
"b":{
"barAge":375478040,
"barDate":1471400178308,
"barName":"name_-1233383964"
},
"c":{
"barAge":-1043862971,
"barDate":1471400178308,
"barName":"name_-823025454"
}
} b:{"barAge":375478040,"barDate":1471400178308,"barName":"name_-1233383964"}
c:{"barAge":-1043862971,"barDate":1471400178308,"barName":"name_-823025454"}
a:{"barAge":877829686,"barDate":1471400178308,"barName":"name_558391664"} array2JSON()
["a","b","c"]
a
b
c
["a","b","c"] array2JSON2()
[{
"barAge":-842219577,
"barDate":1471400178310,
"barName":"name_-1204063138"
},{
"barAge":1450191787,
"barDate":1471400178310,
"barName":"name_650041812"
},{
"barAge":-732707567,
"barDate":1471400178310,
"barName":"name_159117539"
}] {"barAge":-842219577,"barDate":1471400178310,"barName":"name_-1204063138"}
{"barAge":1450191787,"barDate":1471400178310,"barName":"name_650041812"}
{"barAge":-732707567,"barDate":1471400178310,"barName":"name_159117539"}
[{"barAge":-842219577,"barDate":1471400178310,"barName":"name_-1204063138"},{"barAge":1450191787,"barDate":1471400178310,"barName":"name_650041812"},{"barAge":-732707567,"barDate":1471400178310,"barName":"name_159117539"}] map2JSON()
{"a":"aaa","b":"bbb","c":"ccc"}
b--->bbb
c--->ccc
a--->aaa