本文参考:http://www.tuicool.com/articles/zUbQfa

还可参考:https://www.iflym.com/index.php/code/alibaba-fastjson-json-serializer-chapter-source-analyse-one-global-analyse.html

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.2 如果获得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

FastJson的使用方法总结的更多相关文章

  1. Fastjson简单使用方法

    一.简单数据的序列化 pubic class UserInfo implements Serializable{ private String name; private int age; publi ...

  2. FastJson一些常见方法(API):处理JSON变得好简单

    fastjson是目前java语言中最快的json库,比自称最快的jackson速度要快,第三方独立测试结果说明比gson快大约6倍 JSON帮助类 这个可以做一个实例研究代码,也可以作为一个工具类 ...

  3. 使用fastjson的parseObject方法将json字符串转换成Map 或者List

    fastjson 转换成map HashMap<String,String> map = JSON.parseObject(jsonStr,new TypeReference<Has ...

  4. J2EE项目开发中常用到的公共方法

    在项目IDCM中涉及到多种工单,包括有:服务器|网络设备上下架工单.服务器|网络设备重启工单.服务器光纤网线更换工单.网络设备撤线布线工单.服务器|网络设备替换工单.服务器|网络设备RMA工单.通用原 ...

  5. fastJSON☞JSONParameters☞时区的修改☞时间最后有一个"Z"

    why... 为什么会有这个问题; 由于近期用到需要将数据序列化... 最终选择了fastJSON(版本为1.)来实现. 但是发现了一个问题,表中有一个dateTime类型的字段, 本来数据库中存入的 ...

  6. 一个由proguard与fastJson引起的血案

    更多内容在这里查看 https://ahangchen.gitbooks.io/windy-afternoon/content/ 更新微信sdk导致ComposeData中的内部类ComposeDat ...

  7. 一个由proguard与fastJson引起的血案(转)

    更新微信sdk导致ComposeData中的内部类ComposeDataSender方法被混淆 根本原因,fastjson使用姿势不对. 问题描述: 一个发件人列表里,应当呈现的数据(这里命名为Com ...

  8. 【问题排查】fastjson线上排坑记

    前言 版本上线时发现fastjson的toString方法的返回的字符串与与之前版本的toString方法返回的字符串不相同,这导致依赖toString进行md5计算所得到的结果不相同,更进一步导致其 ...

  9. 关于FastJSON

    https://github.com/alibaba/fastjson/wiki/Quick-Start-CN FastJSON常见问题 FastJson和get方法的问题 使用SimplePrope ...

随机推荐

  1. Spring REST实践之Error Handling

    Error Responses 在REST API中,HTTP状态码有非常重要的作用.API开发者应该坚持为每一个请求返回一个正确合适的状态码,而且应该在响应body中包含有用的.细粒度的错误信息.这 ...

  2. Head First设计模式-单例模式

    一.整体代码 Singleton.java public class Singleton { private static Singleton uniqueInstance; // other use ...

  3. 图片懒加载 lazyload

    添加引用 <script type="text/javascript" src="lazyload/yahoo-dom-event.js">< ...

  4. 无责任Windows Azure SDK .NET开发入门篇三[使用Azure AD 管理用户信息--3.3 Details用户详细信息]

    3.3 Details用户详细信息 用户详细信息是通过objectId获取.代码如下 public async Task<ActionResult> Details(string obje ...

  5. c语言-格式控制字符 %XXd 用法

    d格式字符 用来输出十进制整数,有以下几种用法: 1. %d, 按整型数据的实际长度输出. 2.  %md,m为指定输出的整型位数的宽度,如果整型数据的实际位数小于m,则左端补以空格,如果大于m,则按 ...

  6. OpenStack tokens id获取测试

     

  7. 用Java实现菱形的打印输出

    import java.util.Scanner; public class dengyao2 { public dengyao2() { super(); } public static void ...

  8. Watch​Kit Learning Resources

    查看原文:http://leancodingnow.com/watch-kit-learning-resources/  WatchKit是Apple发布的用来开发Apple Watch应用的框架,本 ...

  9. oracle存储过程实例

    oracle存储过程实例 分类: 数据(仓)库及处理 2010-05-03 17:15 1055人阅读 评论(2)收藏 举报 认识存储过程和函数 存储过程和函数也是一种PL/SQL块,是存入数据库的P ...

  10. C语言中的函数

    C语言中的函数 目录 概述——对函数的理解 C语言中函数的定义和声明 函数允许的参数类型 函数允许的返回类型 递归 概述 由于有些代码段在编写程序的时候经常会用到,此时我们为了减少代码文件的长度和增加 ...