- tags:java,json,javascript
- categories:筆記
- date: 2016-11-16 20:18:52
在日常的開發(fā)中辨嗽,在前后端的數(shù)據(jù)傳輸與處理中夕膀,總會(huì)遇到j(luò)ava與json的數(shù)據(jù)轉(zhuǎn)換睛廊,javascript內(nèi)json與string之間的轉(zhuǎn)換等姆吭。所以就想總結(jié)看看這三個(gè)之間是如何轉(zhuǎn)換的噪馏,可以有那些方式進(jìn)行轉(zhuǎn)換呢序苏?這3J的轉(zhuǎn)換也總會(huì)與string字符串類型有關(guān)刊懈,因?yàn)樽址谖覀兂绦蛑泻?jiǎn)直不能再常見了这弧。o(≧v≦)o。虚汛。匾浪。所以咧,就打算用具體代碼實(shí)例來看看它們是如何進(jìn)行數(shù)據(jù)處理的卷哩,下一次若是有這種類似的需求蛋辈,就可以很快把代碼擼出來了,也是基本功的問題将谊。
下面就根據(jù)目前我的學(xué)習(xí)知識(shí)冷溶,總結(jié)以下它們各自之間的關(guān)系和轉(zhuǎn)換過程。
Java與Json
其中最重要也最長(zhǎng)使用的就是后臺(tái)的java與json數(shù)據(jù)的轉(zhuǎn)換尊浓,包括java pojo轉(zhuǎn)成json字符串逞频,再通過response輸出到瀏覽器前端頁面進(jìn)行渲染等其他處理,當(dāng)然也有眠砾,從前端獲取json格式字符串虏劲,到后臺(tái)接收數(shù)據(jù)后托酸,將字符串轉(zhuǎn)換成bean或者集合等等褒颈。所以,java與json轉(zhuǎn)化的工具庫也是挺多的励堡,主要的包括以下幾種:Jackson,Fastjson,Google-Gson,Json-lib谷丸。。等等应结,具體的可以參考該篇文章Java 的 JSON 開源類庫選擇比較
下面就說說主要使用的幾種工具庫把刨疼。。在此之前鹅龄,把幾個(gè)類庫需要用到的基礎(chǔ)數(shù)據(jù)準(zhǔn)備好揩慕,包括一個(gè)user,book兩個(gè)bean扮休。
public class User {
private int id;
private String userName;
private String password;
private int age;
private String phoneNumber;
private String address;
private List<Books> lbooks;
//getter setter
...
}
public class Books {
private String author;
private String price;
private String name;
//getter setter
...
}
構(gòu)造的簡(jiǎn)單基礎(chǔ)數(shù)據(jù)迎卤,這些數(shù)據(jù)都是被下面幾種庫所共用的:
public User user1;
public User user2;
public List<User> lusers = new ArrayList<User>();
public List<Books> lbooks = new ArrayList<Books>();
public Map<Integer,User> musers = new HashMap<Integer,User>();
@Before
public void init(){
initUsers();
lusers.add(user1);
lusers.add(user2);
musers.put(1, user1);
musers.put(2, user2);
}
public void initUsers(){
user1 = new User();
user1.setId(1);
user1.setUserName("heiOne");
user1.setPassword("aa");
user1.setPhoneNumber("1234");
user1.setAge(20);
user1.setAddress("CN.GZ");
user2 = new User();
user2.setId(2);
user2.setUserName("heiTwo");
user2.setPassword("bb");
user2.setPhoneNumber("56789");
user2.setAge(30);
user2.setAddress("CN.SH");
Books b1 = new Books();
b1.setAuthor("泰戈?duì)?);
b1.setPrice("50.00");
b1.setName("飛鳥集");
Books b2 = new Books();
b2.setAuthor("司湯達(dá)");
b2.setPrice("40.00");
b2.setName("紅與黑");
Books b3 = new Books();
b3.setAuthor("塞林格");
b3.setPrice("30.00");
b3.setName("麥田里的守望者");
lbooks.add(b1);
lbooks.add(b2);
List<Books> cbooks = new ArrayList<Books>();
cbooks.addAll(lbooks);
user1.setLbooks(lbooks);
cbooks.add(b3);
user2.setLbooks(cbooks);
}
其中,User中包含Books的集合屬性玷坠,為了測(cè)試復(fù)合結(jié)構(gòu)的數(shù)據(jù)集合蜗搔。
-
Jackson:
Jackjson工具庫功能挺強(qiáng)大的劲藐,可以讀取文件流獲取字節(jié)碼來處理json字符串,也能對(duì)樹模型操作樟凄,提供了api總有關(guān)于節(jié)點(diǎn)的構(gòu)建操作聘芜。當(dāng)然了,也能處理與java對(duì)象的雙向轉(zhuǎn)換缝龄。這點(diǎn)其實(shí)可以從Jackson的maven庫配置的artifactId可以看到汰现,提供對(duì)應(yīng)的不同模塊功能的處理。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-base -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-base</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.jaxrs/jackson-jaxrs-json-provider -->
<dependency>
<groupId>com.fasterxml.jackson.jaxrs</groupId>
<artifactId>jackson-jaxrs-json-provider</artifactId>
<version>2.8.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-annotations -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.8.0</version>
</dependency>
下面通過編寫的一個(gè)測(cè)試用例類JavaAndJsonWithJackson.java來看看具體的操作二拐。對(duì)于功能性較強(qiáng)的Jackson服鹅,我們只是關(guān)注它的java與json之間轉(zhuǎn)換的部分,它的核心類就是ObjectMapper,有興趣學(xué)習(xí)更多內(nèi)容的可以自行度娘百新。(不過話說連jackson官網(wǎng)都被xx了,汗...)
總的來說企软,若是java類型想要轉(zhuǎn)成json格式字符串,就用writeValueAsString
等格式方法饭望;若是json字符串要轉(zhuǎn)成java類型對(duì)象仗哨,則使用readValue
方法。
Java POJO與Json之間的轉(zhuǎn)換:
對(duì)于java數(shù)據(jù)轉(zhuǎn)成json铅辞,大多都是writeValue*相關(guān)的方法厌漂。這種也是最簡(jiǎn)單基礎(chǔ)的用法啦...
@Test
public void javaPojoPointToJsonStr() throws Exception{
ObjectMapper om = new ObjectMapper();
//java pojo轉(zhuǎn)換成json字符串
String ustr = om.writeValueAsString(user1);
System.out.println("java user pojo 轉(zhuǎn)換成json字符串:"+ ustr);
//json 字符串轉(zhuǎn)成java pojo
User jsonUser = om.readValue(ustr, User.class);
System.out.println("user json 字符串轉(zhuǎn)成User.class pojo"+jsonUser);
}
//輸出:可以在www.bejson.com在線格式化校驗(yàn)json字符串
java user pojo 轉(zhuǎn)換成json字符串:
{
"id": 1,
"userName": "heiOne",
"password": "aa",
"age": 20,
"phoneNumber": "1234",
"address": "CN.GZ",
"lbooks": [
{
"author": "泰戈?duì)?,
"price": "50.00",
"name": "飛鳥集"
},
{
"author": "司湯達(dá)",
"price": "40.00",
"name": "紅與黑"
}
]
}
user json 字符串轉(zhuǎn)成User.class pojo:(輸出格式是通過toString定義的)
User.class pojoUser
[id=1, userName=heiOne, password=aa, age=20, phoneNumber=1234, address=CN.GZ,
lbooks=[Books [author=泰戈?duì)? price=50.00, name=飛鳥集],
Books [author=司湯達(dá), price=40.00, name=紅與黑]]]
Java List集合與Json之間的轉(zhuǎn)換:
其實(shí)也都差不多,只是當(dāng)json字符串轉(zhuǎn)成java list集合時(shí)候斟珊,每個(gè)list內(nèi)的數(shù)據(jù)類型是:LinkedHashMap,然后可以通過key苇倡,value形式取出每個(gè)數(shù)據(jù)。
@Test
public void javaListPointToJsonStr() throws Exception{
ObjectMapper om = new ObjectMapper();
//java list轉(zhuǎn)換成json字符串
String listStr = om.writeValueAsString(lusers);
System.out.println("java list集合轉(zhuǎn)換為json字符串:"+listStr);
//list形式j(luò)son字符串轉(zhuǎn)換成java list. List<User>不可轉(zhuǎn)
List uList = om.readValue(listStr, List.class);
System.out.println("list json 轉(zhuǎn)換成java list集合:"+uList);
for(int i=0;i<uList.size();i++){
// System.out.println(uList.get(i).getClass()); //LinkedHashMap
LinkedHashMap lhm = (LinkedHashMap) uList.get(i);
System.out.println(lhm.get("userName"));
System.out.println(lhm.get("lbooks"));
}
}
//輸出:
[
{
"id": 1,
"userName": "heiOne",
"password": "aa",
"age": 20,
"phoneNumber": "1234",
"address": "CN.GZ",
"lbooks": [
{
"author": "泰戈?duì)?,
"price": "50.00",
"name": "飛鳥集"
},
{
"author": "司湯達(dá)",
"price": "40.00",
"name": "紅與黑"
}
]
},
{
"id": 2,
"userName": "heiTwo",
"password": "bb",
"age": 30,
"phoneNumber": "56789",
"address": "CN.SH",
"lbooks": [
{
"author": "泰戈?duì)?,
"price": "50.00",
"name": "飛鳥集"
},
{
"author": "司湯達(dá)",
"price": "40.00",
"name": "紅與黑"
},
{
"author": "塞林格",
"price": "30.00",
"name": "麥田里的守望者"
}
]
}
]
heiOne
[{author=泰戈?duì)? price=50.00, name=飛鳥集}, {author=司湯達(dá), price=40.00, name=紅與黑}]
heiTwo
[{author=泰戈?duì)? price=50.00, name=飛鳥集}, {author=司湯達(dá), price=40.00, name=紅與黑},
{author=塞林格, price=30.00, name=麥田里的守望者}]
Java Map集合與Json之間的轉(zhuǎn)換:
使用方法和輸出都與list集合差不多囤踩,就不在多說了旨椒。
@Test
public void javaMapPointToJsonStr()throws Exception{
ObjectMapper om = new ObjectMapper();
//java map ---> json
String mapStr = om.writeValueAsString(musers);
System.out.println("java map集合轉(zhuǎn)換為json字符串:"+mapStr);
//map json --> java map
Map umap = om.readValue(mapStr, Map.class);
System.out.println("map json 轉(zhuǎn)換為java map:"+umap);
// System.out.println(umap.get("1").getClass());
for(int i=1;i<=umap.size();i++){
LinkedHashMap lhm = (LinkedHashMap) umap.get(String.valueOf(i));
System.out.println(lhm.get("userName"));
System.out.println(lhm.get("lbooks"));
}
}
-
FastJson:
下面這個(gè)就是阿里的fastjson啦,感覺也挺強(qiáng)大和易用的堵漱,主要是通過com.alibaba.fastjson.JSON對(duì)象進(jìn)行轉(zhuǎn)換综慎。
若是java類型轉(zhuǎn)成json格式字符串,可以使用toJSONString
方法勤庐,反之示惊,可以使用parseObject
或者parseArray
等方法。想了解更多愉镰,可以查看fastjson的github項(xiàng)目
這里的例子輸出可以參考jackson的test測(cè)試用例米罚。這里多說一點(diǎn),fastjson在輸出字符串的時(shí)候丈探,若是數(shù)據(jù)相同則會(huì)出現(xiàn)$ref
引用符號(hào)出現(xiàn)录择,在測(cè)試的時(shí)候,發(fā)現(xiàn)若是將帶有這個(gè)引用符號(hào)的json字符串轉(zhuǎn)換成java類型對(duì)象會(huì)出現(xiàn)null值的現(xiàn)象。
maven庫配置:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
Java POJO與Json之間的轉(zhuǎn)換:
@Test
public void javaPojoPointToJsonStr() throws Exception{
//java pojo轉(zhuǎn)換成json字符串
String ustr = JSON.toJSONString(user1);
System.out.println("java user pojo 轉(zhuǎn)換成json字符串:"+ ustr);
//
//json 字符串轉(zhuǎn)成java pojo
User jsonUser = JSON.parseObject(ustr,User.class);
System.out.println("user json 字符串轉(zhuǎn)成User.class pojo"+jsonUser);
}
Java List集合與Json之間的轉(zhuǎn)換:
@Test
public void javaListPointToJsonStr() throws Exception{
// java list轉(zhuǎn)換成json字符串
String listStr = JSON.toJSONString(lusers);
System.out.println("java list集合轉(zhuǎn)換為json字符串:"+listStr);
// list形式j(luò)son字符串轉(zhuǎn)換成java list. JSON.parseObject
List uList = JSON.parseObject(listStr, List.class);
System.out.println("list json 轉(zhuǎn)換成java list集合:"+uList);
for(int i=0;i<uList.size();i++){
// System.out.println(uList.get(i).getClass());//JSONObject
JSONObject jo = (JSONObject) uList.get(i);
// System.out.println(jo.size());
System.out.println(jo.get("userName"));
System.out.println(jo.get("lbooks"));
}
//JSON.parseArray
List<User> uList1 = JSON.parseArray(listStr, User.class);
System.out.println(uList1);
for(User u : uList1){
System.out.println(u.getUserName());
}
}
Java Map集合與Json之間的轉(zhuǎn)換:
@Test
public void javaMapPointToJsonStr()throws Exception{
// //java map ---> json
String mapStr = JSON.toJSONString(musers);
System.out.println("java map集合轉(zhuǎn)換為json字符串:"+mapStr);
//
//map json --> java map
//http://blog.csdn.net/weixiaodedao/article/details/51790790 解決使用fastJson中出現(xiàn)$ref問題
JSONObject umap = JSON.parseObject(mapStr); //引用$ref,null
System.out.println("map json 轉(zhuǎn)換為java map:"+umap);
// System.out.println(umap.get("1").getClass());
for(int i=1;i<=umap.size();i++){
JSONObject obj = (JSONObject) umap.get(String.valueOf(i)); //com.alibaba.fastjson.JSONObject
System.out.println(obj.get("userName"));
}
}
-
JSON-lib:
若是要轉(zhuǎn)換成json格式字符串可以使用JSONObject.fromObject
或者JSONArray.fromObject
方法糊肠;若是要轉(zhuǎn)換成集合或者java bean則可以使用這些方法JSONArray.toList
(已廢棄)或者JSONArray.toArray
,至于map的轉(zhuǎn)換辨宠,可以要自己來抽取內(nèi)部數(shù)據(jù)實(shí)現(xiàn)調(diào)整了。
maven庫配置:
<!-- https://mvnrepository.com/artifact/net.sf.json-lib/json-lib -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
Java POJO與Json之間的轉(zhuǎn)換:
//http://ryxxlong.iteye.com/blog/583862 json-lib使用方法
@Test
public void javaPojoPointToJsonStr() throws Exception{
//java pojo轉(zhuǎn)換成json字符串,都是先轉(zhuǎn)換成JSONObject對(duì)象
JSONObject jsonObject = JSONObject.fromObject(user1);
String ustr = jsonObject.toString();
System.out.println("java user pojo 轉(zhuǎn)換成json字符串:"+ ustr);
// json 字符串轉(zhuǎn)成java pojo
User jsonUser = (User) JSONObject.toBean(jsonObject, User.class);
System.out.println("user json 字符串轉(zhuǎn)成User.class pojo"+jsonUser);
}
Java List集合與Json之間的轉(zhuǎn)換:
@Test
public void javaListAndArrayPointToJsonStr() throws Exception{
// java list轉(zhuǎn)換成json字符串
JSONArray jsonArray = JSONArray.fromObject(lusers);
String listStr = jsonArray.toString();
System.out.println("java list集合轉(zhuǎn)換為json字符串:"+listStr);
// list形式j(luò)son字符串轉(zhuǎn)換成java list.
// List<User> uList = JSONArray.toList(jsonArray, User.class); //toList已被廢棄
User[] array = (User[]) JSONArray.toArray(jsonArray, User.class);
// System.out.println("list"+uList);
System.out.println("array:"+array);
//JSON.parseArray
// for(User u : uList){
// System.out.println(u.getUserName());
// }
for(int i=0;i<array.length;i++){
System.out.println(array[i].getUserName());
}
}
Java Map集合與Json之間的轉(zhuǎn)換:
若是想看看更細(xì)節(jié)的map與json轉(zhuǎn)換货裹,可以參考這篇文章:<u>采用json-lib進(jìn)行Map與Json轉(zhuǎn)換</u>
@Test
public void javaMapPointToJsonStr()throws Exception{
// //java map ---> json 這里map<key,value>中必須為string類型
Map<String,String> tmp = new HashMap<String,String>();
tmp.put("one", "apple");
tmp.put("two", "hehe");
JSONObject ja= JSONObject.fromObject(tmp);
System.out.println("java map集合轉(zhuǎn)換為json字符串:"+ja.toString());//{"two":"hehe","one":"apple"}
Map<String,Map<String,String>> mmtmp = new HashMap<String,Map<String,String>>();
Map<String,String> mtmp = new HashMap<String,String>();
mtmp.put("inner", "test");
mmtmp.put("a", mtmp);
mmtmp.put("b", mtmp);
JSONArray jsonArray= JSONArray.fromObject(mmtmp);
System.out.println("java map集合轉(zhuǎn)換為json字符串:"+jsonArray.toString());//[{"b":{"inner":"test"},"a":{"inner":"test"}}]
//
//更多使用JSON-LIB 對(duì)map與json轉(zhuǎn)換可以參考該片文章:https://my.oschina.net/heweipo/blog/386808
}
關(guān)于java與json數(shù)據(jù)的基本轉(zhuǎn)換常用工具使用方法就寫到這嗤形,當(dāng)然這些都是基礎(chǔ)內(nèi)容,在項(xiàng)目開發(fā)中弧圆,實(shí)則可以自己在封裝工具類對(duì)需求的業(yè)務(wù)進(jìn)行處理赋兵。
Json與Javascript
除了java與json之間需要轉(zhuǎn)換,經(jīng)常在開發(fā)web項(xiàng)目時(shí)候搔预,從后端得到的json字符串在前端處理總會(huì)要轉(zhuǎn)換成json對(duì)象的需求霹期,反之亦然。所以拯田,來看看在前端頁面中的script腳本中是如何處理json數(shù)據(jù)的历造?
其實(shí),javascript原生的就有對(duì)json數(shù)據(jù)轉(zhuǎn)換的方法船庇】圆總的來說,在前端頁面的script腳本中:json字符串想轉(zhuǎn)換成json對(duì)象鸭轮,可以使用
eval('(' + jsonstr + ')')
方法臣淤;json對(duì)象要轉(zhuǎn)換成string字符串則可以使用JSON.stringify(jsonObject)
方法。
下面看看后端輸出json字符串到前端后窃爷,前端如何處理json字符串的:
- 后端java代碼:使用jackson來將list集合轉(zhuǎn)換成json字符串輸出:
public List<User> lusers = new ArrayList<User>();
@RequestMapping(value="/jj.do",method=RequestMethod.GET)
public String toJJPage(HttpServletRequest request) throws Exception{
if(lusers.size()<1)
initData();
ObjectMapper om = new ObjectMapper();
//java list轉(zhuǎn)換成json字符串
String listStr = om.writeValueAsString(lusers);
System.out.println("java list集合轉(zhuǎn)換為json字符串:"+listStr);
request.setAttribute("lusers", listStr);
return "js_json";
}
-
在看使用springmvc將頁面跳轉(zhuǎn)到j(luò)s_json.jsp中:
可以看到邑蒋,將后端中的request域中的lusers
屬性輸出是一串json格式字符串,然后在script腳本中使用方法eval('('+str+')'),JSON.stringify方法將json字符串和json對(duì)象互相轉(zhuǎn)換按厘。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
Object listUser = request.getAttribute("lusers");
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>">
<title>Javascript-json</title>
</head>
<body>
List user: <%=listUser%>
<script type="text/javascript">
var luser = '<%=listUser%>';
alert(luser+':'+typeof(luser)); //string
//JSON字符串轉(zhuǎn)換為JSON對(duì)象
var json = eval('(' + luser + ')'); //可用
var json = JSON.parse(luser);
alert(json+':'+typeof(json));
alert(json[0].userName);
//將json對(duì)象轉(zhuǎn)換為json格式字符串
var userJson = JSON.stringify(json); //ok
alert('json object --> json string:'+userJson);
</script>
</body>
</html>
Java與Javascript
咳咳...這個(gè)就是最簡(jiǎn)單了医吊。通常需要將java對(duì)象轉(zhuǎn)換成javascript對(duì)象時(shí)候,一般就是在前端頁面中刻剥,例如jsp等遮咖。在<% %>
中可以定義或者java代碼對(duì)象滩字,可以通過<%=variable %>
表達(dá)式可以獲取java對(duì)象造虏。結(jié)合這些特性,那么要在script腳本中使用java對(duì)象麦箍,只需要用兩個(gè)'
單引號(hào)將java對(duì)象引起來即可賦值給javascript變量漓藕。
可以參照上面json與javascript轉(zhuǎn)換中的jsp頁面中就有使用:
<script type="text/javascript">
var luser = '<%=listUser%>'; //將java對(duì)象賦值給javascript變量
alert(luser+':'+typeof(luser)); //string
</script>
ok,總結(jié)得差不多了,日后有可以完善的在整合啦...( ̄▽ ̄)~*