JSON即JavaScript Object Notation(JavaScript對(duì)象表示法),現(xiàn)在常被作為不同程序之間通信的語(yǔ)言,。算是機(jī)器之間交流的語(yǔ)法規(guī)則的一種,對(duì)于程序員來(lái)講掌握J(rèn)SON的解析變得非常重要,這將有助于我們和程序之間的溝通,。
一個(gè)簡(jiǎn)單的JSON案例如下:
{
"name":"小王同學(xué)",
"age":18,
"pengyou":["張三","李四","王二","麻子",{
"name":"野馬老師",
"info":"像匹野馬一樣狂奔在技術(shù)鉆研的道路上"
}],
"heihei":{
"name":"大長(zhǎng)刀",
"length":"40m"
}
}
下面介紹三種常用的解析方法:
1 Gson
- 將對(duì)象轉(zhuǎn)換為JSON字符串
1. 引入JAR包
2. 在需要轉(zhuǎn)換JSON字符串的位置編寫(xiě)如下代碼即可:
String json = new Gson().toJSON(要轉(zhuǎn)換的對(duì)象);
- 將JSON字符串轉(zhuǎn)換為對(duì)象
1. 引入JAR包
2. 在需要轉(zhuǎn)換Java對(duì)象的位置, 編寫(xiě)如下代碼
對(duì)象 = new Gson().fromJson(JSON字符串,對(duì)象類型.class);
案例Demo:
public class Demo1 {
public static void main(String[] args) {
// 創(chuàng)建json對(duì)象
Gson gson = new Gson();
// 轉(zhuǎn)換成json {"id":"100","name":"金蘋(píng)果","info":"種植蘋(píng)果"}
Book book = new Book("100", "金蘋(píng)果", "種植蘋(píng)果");
String s = gson.toJson(book);
System.out.println(s);
// json轉(zhuǎn)字符串
Book book1 = gson.fromJson(s, Book.class);
System.out.println(book1);
}
}
public static void main(String[] args) {
// 創(chuàng)建json對(duì)象
Gson gson = new Gson();
// json轉(zhuǎn)字符串 {"id":"100","name":"金蘋(píng)果","info":"種植蘋(píng)果","page":["鋤禾日當(dāng)午","汗滴禾下土"]}
HashMap data = gson.fromJson("{\"id\":\"100\",\"name\":\"金蘋(píng)果\",\"info\":\"種植蘋(píng)果\",\"page\":[\"鋤禾日當(dāng)午\",\"汗滴禾下土\"]}", HashMap.class);
System.out.println(data.get("page"));
// json中的數(shù)組會(huì)被轉(zhuǎn)成List集合
System.out.println(data.get("page").getClass());
List page = (List) data.get("page");
System.out.println(page.get(1));
}
2 FastJson
- 將對(duì)象轉(zhuǎn)換為JSON字符串
轉(zhuǎn)換JSON字符串的步驟:
1. 引入JAR包
2. 在需要轉(zhuǎn)換JSON字符串的位置編寫(xiě)如下代碼即可
- 將JSON字符串轉(zhuǎn)換為對(duì)象
1. 引入JAR包
2. 在需要轉(zhuǎn)換Java對(duì)象的位置, 編寫(xiě)如下代碼:
類型 對(duì)象名=JSON.parseObject(JSON字符串, 類型.class);
或
List<類型> list=JSON.parseArray(JSON字符串,類型.class);
案例Demo:
public static void main(String[] args) {
Book book = new Book("1002", "唐詩(shī)300首","床前明月光");
// 轉(zhuǎn)換 {"id":"1002","info":"床前明月光","name":"唐詩(shī)300首"}
String json = JSON.toJSONString(book);
System.out.println(json);
// json轉(zhuǎn)對(duì)象
Book book1 = JSON.parseObject("{\"id\":\"1002\",\"info\":\"床前明月光\",\"name\":\"唐詩(shī)300首\"}", Book.class);
System.out.println(book1.getName());
}
public static void main(String[] args) {
// json轉(zhuǎn)數(shù)組 ["一二三", "二三四", "三四五"]
List<String> strings = JSON.parseArray("[\"一二三\", \"二三四\", \"三四五\"]", String.class);
System.out.println(strings.get(2));
}
3?Jackson
- 將JSON字符串轉(zhuǎn)換為對(duì)象
步驟:
1. 導(dǎo)入jackson的相關(guān)jar包
2. 創(chuàng)建Jackson核心對(duì)象 ObjectMapper
3. 調(diào)用ObjectMapper的相關(guān)方法進(jìn)行轉(zhuǎn)換
readValue(json字符串?dāng)?shù)據(jù),Class)
@Test
public void tes5() throws Exception {
String json = "{\"gender\":\"男\(zhòng)",\"name\":\"張三\",\"age\":23}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
System.out.println(person);// 輸出Person類的toString()
}
1. 導(dǎo)入jackson的相關(guān)jar包
2. 創(chuàng)建Jackson核心對(duì)象 ObjectMapper
3. 調(diào)用ObjectMapper的相關(guān)方法進(jìn)行轉(zhuǎn)換
writeValue(參數(shù)1,obj):
參數(shù)1:
File:將obj對(duì)象轉(zhuǎn)換為JSON字符串,并保存到指定的文件中
Writer:將obj對(duì)象轉(zhuǎn)換為JSON字符串,并將json數(shù)據(jù)填充到字符輸出流中
OutputStream:將obj對(duì)象轉(zhuǎn)換為JSON字符串,并將json數(shù)據(jù)填充到字節(jié)輸出流中
writeValueAsString(obj):將對(duì)象轉(zhuǎn)為json字符串
Person p = new Person();
p.setName("張三");
p.setAge(23);
p.setGender("男");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(p);
System.out.println(json);
//writeValue,將數(shù)據(jù)寫(xiě)到d://a.txt文件中
mapper.writeValue(new File("d://a.txt"), p);
//writeValue,將數(shù)據(jù)關(guān)聯(lián)到Writer中
mapper.writeValue(new FileWriter("d://b.txt"),p);
案例:校驗(yàn)用戶名是否存在
服務(wù)器響應(yīng)的數(shù)據(jù),在客戶端使用時(shí),要想當(dāng)做json數(shù)據(jù)格式使用,。有兩種解決方案:
1. $.get(type):將最后一個(gè)參數(shù)type指定為"json"
2. 在服務(wù)器端設(shè)置MIME類型
response.setContentType("application/json;charset=utf-8");
前端界面:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>注冊(cè)頁(yè)面</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$("#username").blur(function () {
var username = $(this).val();
// 發(fā)送ajax請(qǐng)求
//期望服務(wù)器響應(yīng)回的數(shù)據(jù)格式:{"userExsit":true,"msg":"此用戶名太受歡迎,請(qǐng)更換一個(gè)"}
// {"userExsit":false,"msg":"用戶名可用"}
$.get("findUserServlet",{username:username}, function (data) {
var span = $("#s_username");
if (data.userExsit){
span.css("color","red");
span.html(data.msg);
}else {
span.css("color","green");
span.html(data.msg);
}
},"json");
});
});
</script>
</head>
<body>
<form>
<input type="text" id="username" name="username" placeholder="請(qǐng)輸入用戶名">
<span id="s_username"></span>
<br>
<input type="password" name="password" placeholder="請(qǐng)輸入密碼"><br>
<input type="submit" value="注冊(cè)"><br>
</form>
</body>
</html>
相應(yīng)的servlet:
@WebServlet("/findUserServlet")
public class FindUserServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 1.獲取用戶名
String username = request.getParameter("username");
// 2.調(diào)用service層判斷用戶名是否存在
//設(shè)置響應(yīng)的數(shù)據(jù)格式為json
response.setContentType("application/json;charset=utf-8");
Map<String , Object> map = new HashMap<>();
if("tom".equals(username)){
//存在
map.put("userExsit",true);
map.put("msg","此用戶名太受歡迎,請(qǐng)更換一個(gè)");
}else{
//不存在
map.put("userExsit",false);
map.put("msg","用戶名可用");
}
//將map轉(zhuǎn)為json,并且傳遞給客戶端
//將map轉(zhuǎn)為json
ObjectMapper mapper = new ObjectMapper();
//并且傳遞給客戶端
mapper.writeValue(response.getWriter(),map);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
}
大家可以通過(guò)我的微信公眾號(hào)【N小王日記】獲取大禮包,。