一、JSON
1.JSON是什么
JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,它是js提供的一种数据交换格式!
2.json的语法
- {}:是对象!
- 属性名必须使用双引号括起来!单引不行!!!
- 属性值:
- null
- 数值
- 字符串
- 数组:使用[]括起来
- boolean值:true和false
3.应用json
- var person = {"name":"zhangSan", "age":18, "sex":"male"};
- alert(person.name+","+person.age+","+person.sex);
4.json与xml比较
- 可读性:XML胜出
- 解析难度:JSON本身就是JS对象(主场作战),所以简单很多
- 流行度:XML已经流行好多年,但在AJAX领域,JSON更受欢迎。
5.示例:
1 package web.servlet;
2
3 import javax.servlet.ServletException;
4 import javax.servlet.annotation.WebServlet;
5 import javax.servlet.http.HttpServlet;
6 import javax.servlet.http.HttpServletRequest;
7 import javax.servlet.http.HttpServletResponse;
8 import java.io.IOException;
9
10 @WebServlet(name = "AServlet",urlPatterns = "/AServlet")
11 public class AServlet extends HttpServlet {
12 protected void doGet(HttpServletRequest request, HttpServletResponse response)
13 throws ServletException, IOException {
14 /*
15 * 向客户端发送json串
16 * */
17 String str = "{"name":"zhangsan","age":18,"sex":"male"}";
18 response.getWriter().print(str);
19 System.out.println(str);
20 }
21 }
1 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
2 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
3 <html>
4 <head>
5 <title>Title</title>
6 <script type="text/javascript">
7 //创建异步对象
8 function createXMLHttpRequest() {
9 try {
10 return new XMLHttpRequest();
11 }catch (e){
12 try{
13 return ActiveXObject("Msxml2.XMLHTTP");
14 }catch (e){
15 try {
16 return ActiveXObject("Microsoft.XMLHTTP");
17 }catch (e) {
18 alert("您用的是什么浏览器啊?")
19 throw e;
20 }
21 }
22 }
23 }
24 window.onload = function () {
25 //获取btn元素
26 var btn = document.getElementById("btn");
27 btn.onclick = function () { //给按钮的点击事件上添加监听
28 //使用ajax得到服务器端响应,把结果显示到h3中
29 //1、得到request
30 var xmlHttp = createXMLHttpRequest();
31 //2、连接
32 xmlHttp.open("GET","<c:url value="/AServlet"/>",true);
33 //3、发送
34 xmlHttp.send(null);
35 //4、给xmlHttp的状态改变事件上添加监听
36 xmlHttp.onreadystatechange =function () {
37 //双重判断
38 if(xmlHttp.readyState == 4 && xmlHttp.status == 200) {
39 var text = xmlHttp.responseText;//它是一个json串
40 var person = eval("("+text+")");
41 var s = person.name+","+person.age+","+person.sex;
42 document.getElementById("h3").innerHTML = s;
43 }
44 };
45
46 };
47 };
48 </script>
49 </head>
50 <body>
51 <%-- 点击按钮后,把服务器响应的数据显示到h3元素中 --%>
52 <button id="btn">点击这里</button>
53 <h1>JSON之Hello World</h1>
54 <h3 id="h3"></h3>
55 </body>
56 </html>
二、json-lib
1. 是什么?
- 它可以把javabean转换成json串
- json-lib.jar下载链接:https://sourceforge.net/projects/json-lib/files/json-lib/json-lib-2.4/
2. 核心类
- JSONObject --> Map
- toString();
- JSONObject map = JSONObject.fromObject(person):把对象转换成JSONObject对象
- JSONArray --> List
- toString()
- JSONArray jsonArray = JSONObject.fromObject(list):把list转换成JSONArray对象
3.示例:
1 package demo1;
2
3 import Person.Person;
4 import net.sf.json.JSONArray;
5 import net.sf.json.JSONObject;
6 import org.junit.Test;
7 import java.util.ArrayList;
8 import java.util.List;
9
10 /**
11 * 演示JSON-lib小工具
12 */
13 public class Demo1 {
14 @Test
15 public void fun1() {
16 JSONObject map = new JSONObject();
17 map.put("name","zhangsan");
18 map.put("age",25);
19 map.put("sex","male");
20 String s = map.toString();
21 System.out.println(s);
22 }
23 /*
24 * 当你已经有一个Person对象时,可以把Person转换成JSONObject对象
25 */
26 @Test
27 public void fun2() {
28 Person p = new Person("lisi",32,"female");
29 //把对象转换成JSONObject类型
30 JSONObject map = JSONObject.fromObject(p);
31 System.out.println(map.toString());
32 }
33 /**
34 * JSONArray
35 */
36 @Test
37 public void fun3() {
38 Person p1 = new Person("zhangsan",25,"male");
39 Person p2 = new Person("lisi",32,"female");
40
41 JSONArray list = new JSONArray();
42 list.add(p1);
43 list.add(p2);
44
45 System.out.println(list.toString());
46 }
47 /**
48 * 原来就有一个List,我们需要把List转换成JSONArray
49 */
50 @Test
51 public void fun4 () {
52 Person p1 = new Person("zhangsan",25,"male");
53 Person p2 = new Person("lisi",32,"female");
54 List<Person> list = new ArrayList<Person>();
55 list.add(p1);
56 list.add(p2);
57
58 System.out.println(JSONArray.fromObject(list).toString());
59 }
60 }
三、fastjson主要的使用入口
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。
使用示例:
1 package junit.test; 2 3 import java.util.ArrayList; 4 import java.util.HashMap; 5 import java.util.List; 6 import java.util.Map; 7 8 import com.alibaba.fastjson.JSON; 9 import com.alibaba.fastjson.TypeReference; 10 11 public class TestFastJson { 12 13 static class Person{ 14 private String id ; 15 private String name; 16 private int age ; 17 18 public Person(){ 19 20 } 21 public Person(String id,String name,int age){ 22 this.id=id; 23 this.name=name; 24 this.age=age; 25 } 26 public String getId() { 27 return id; 28 } 29 public void setId(String id) { 30 this.id = id; 31 } 32 public String getName() { 33 return name; 34 } 35 public void setName(String name) { 36 this.name = name; 37 } 38 public int getAge() { 39 return age; 40 } 41 public void setAge(int age) { 42 this.age = age; 43 } 44 @Override 45 public String toString() { 46 return "Person [age=" + age + ", id=" + id + ", name=" + name + "]"; 47 } 48 49 50 } 51 public static void main(String[] args) { 52 method1(); 53 method2(); 54 method3(); 55 method4(); 56 } 57 58 static void method1(){ 59 System.out.println("javabean转化示例开始----------"); 60 Person person = new Person("1","fastjson",1); 61 62 //这里将javabean转化成json字符串 63 String jsonString = JSON.toJSONString(person); 64 System.out.println(jsonString); 65 //这里将json字符串转化成javabean对象, 66 person =JSON.parseObject(jsonString,Person.class); 67 System.out.println(person.toString()); 68 69 System.out.println("javabean转化示例结束----------"); 70 } 71 72 static void method2(){ 73 System.out.println("List<javabean>转化示例开始----------"); 74 75 Person person1 = new Person("1","fastjson1",1); 76 Person person2 = new Person("2","fastjson2",2); 77 List<Person> persons = new ArrayList<Person>(); 78 persons.add(person1); 79 persons.add(person2); 80 String jsonString = JSON.toJSONString(persons); 81 System.out.println("json字符串:"+jsonString); 82 83 //解析json字符串 84 List<Person> persons2 = JSON.parseArray(jsonString,Person.class); 85 //输出解析后的person对象,也可以通过调试模式查看persons2的结构 86 System.out.println("person1对象:"+persons2.get(0).toString()); 87 System.out.println("person2对象:"+persons2.get(1).toString()); 88 89 System.out.println("List<javabean>转化示例结束----------"); 90 } 91 }