一、fastjson
一款Json处理工具包,包括“序列化”和“反序列化”两部分,它具备如下特征:
速度最快,测试表明,fastjson具有极快的性能,超越任其他的Java Json parser。包括自称最快的JackJson;
功能强大,完全支持Java Bean、集合、Map、日期、Enum,支持范型,支持自省。
二、api 接口demo
①、复杂的Object 转为 json
JSON.toJSONString(Object o)
public class ContentData { private List<ContentRes> contents; public List<ContentRes> getContents() {
return contents;
} public void setContents(List<ContentRes> contents) {
this.contents = contents;
} }
public class ContentRes { private boolean success; private String msg; private Long tatal; private List<ContentDO> data; public boolean isSuccess() {
return success;
} public String getMsg() {
return msg;
} public Long getTatal() {
return tatal;
} public List<ContentDO> getData() {
return data;
} public void setSuccess(boolean success) {
this.success = success;
} public void setMsg(String msg) {
this.msg = msg;
} public void setTatal(Long tatal) {
this.tatal = tatal;
} public void setData(List<ContentDO> data) {
this.data = data;
} }
public class ContentDO { private String id; private String title; private String url; public String getId() {
return id;
} public void setId(String id) {
this.id = id;
} public String getTitle() {
return title;
} public void setTitle(String title) {
this.title = title;
} public String getUrl() {
return url;
} public void setUrl(String url) {
this.url = url;
} }
public class Client { public static void main(String[] args) {
String js = JSON.toJSONString(initContentData());
System.out.println(js); } static ContentData initContentData() {
ContentData c = new ContentData();
c.setContents(initContentRess());
return c;
} static ContentRes initContentRes() { ContentRes c = new ContentRes();
c.setData(initContentDOs());
c.setMsg("msg");
c.setSuccess(true);
c.setTatal(100L);
return c;
} static List<ContentRes> initContentRess() {
List<ContentRes> res = new ArrayList<ContentRes>();
res.add(initContentRes());
return res;
} static List<ContentDO> initContentDOs() {
List<ContentDO> res = new ArrayList<ContentDO>();
for (int i = 0; i < 3; i++) {
ContentDO c = new ContentDO();
c.setId("id" + i);
c.setTitle("title" + i);
c.setUrl("url" + i);
res.add(c);
}
return res;
}
}
结果 :
{
"contents": [
{
"data": [
{
"id": "id0",
"title": "title0",
"url": "url0"
},
{
"id": "id1",
"title": "title1",
"url": "url1"
},
{
"id": "id2",
"title": "title2",
"url": "url2"
}
],
"msg": "msg",
"success": true,
"tatal": 100
}
]
}
②、将json 数据转为object 对象
JSON.parseObject(String text, Class<T> clazz)
public static void main(String[] args) {
String js = JSON.toJSONString(initContentData());
System.out.println(js); ContentData obj = JSON.parseObject(js, ContentData.class);
System.out.println(obj); js = JSON.toJSONString(initContentData2());
System.out.println(js);
}
结果 :
三、近来项目,老是遇到一些细节,有必要在此提一下。
①、List 转为json 数据的格式。[...]
[
{},
{},
{}
]
demo,可以见上诉Object转为json数据
②、Array 转为json 数据的格式 。 同上
四、推荐JSON格式化的工具
http://qqe2.com/
http://www.bejson.com/