JSON
Introduction to JSON
-
AJAX first used the data format of XML. The data format of XML is very simple and clear, and easy to write. However, because XML contains too many tags and a very complex structure, it is relatively complicated to parse, so at present, There is almost no use of XML to send data in AJAX. Replaced by a new technology JSON.
-
JSON is the abbreviation of JavaScript Object Notation, and is a data exchange format provided by JS.
-
The JS ON object is essentially a JS object, but this object is special. It can be directly converted to a string, passed in different languages, and converted to objects in other languages through tools.
-
The most commonly used in daily work is asynchronous request + json.
-
For example, there is a JSON object as follows:
-
{“name”:”sunwukong” , ”age”:18 , ”address”:”beijing” }
-
There are three attributes name, age and address in this object
-
If the object is enclosed in single quotes, then it becomes a string
-
‘{“name”:”sunwukong” , ”age”:18 , ”address”:”beijing” }’
-
One advantage of becoming a string is that it can be passed between different languages.
-
For example, if you send JSON as a string to a servlet, you can convert the JSON string into a Java object in Java.
-
JSON is represented by 6 data types
- String
-
Example: "string"
-
Note: Single quotes cannot be used
- digital:
- Example: 123.4
- Boolean value:
- Examples: true, false
- null value:
- Example: null
- Object
- Example child: {“name”: ”sunwukong”, ”age”: 18}
- Array
- Example: [1,"str",true]
Manipulate JSON in JS
- Create JSON object
-
var json = {“name1”:”value1”,”name2”:”value2” , “name3”:[1,”str”,true]};
-
var json = [{“name1”:”value1”},{“name2”:”value2”}];
- Convert JSON object to JSON string
- JSON.stringify(JSON对象)
- Convert JS ON string to JSON object
- JSON.parse(JSON string)
Manipulate JSON in Java
-
In Java, you can read a JSON string from a file, or it can be a JSON string sent by the client, so the first question is how to convert a JSON string into a Java object.
-
First, to parse the JSON string, we need to import third-party tools. At present, there are about three mainstream tools for parsing JSON: json-lib, jackson, and gson. Compared with the use of json-lib, the three parsing tools are more complicated and less efficient. Jackson and gson have higher analytical efficiency. Simple to use, here we take gson as an example to explain.
-
Gson is a JSON parsing tool produced by Google, which is easy to use and has good parsing performance.
-
The core of parsing JSON in Gson is the Gson class, and parsing operations are performed through instances of this class.
-
Convert JSON string to object
@Test
public void JsonToJava(){
Gson gson = new Gson();
String jsonStr = "{\"id\":1001,\"name\":\"张三\",\"age\":22,\"dept_id\":1}";
/*存在map中,键值对*/
Map map = gson.fromJson(jsonStr, Map.class);
System.out.println(map);
/*存到Employee对象中*/
Employee employee = gson.fromJson(jsonStr, Employee.class);
System.out.println(employee);
}
- Convert object to JSON string
@Test
public void JavaToJson(){
/*转换单个对象*/
Employee employee = new Employee();
employee.setId(1001);
employee.setName("张三");
employee.setAge(22);
employee.setDept_id(1);
Department department = new Department();
department.setId(1);
department.setDep_name("研发部");
department.setDep_location("上海");
employee.setDepartment(department);
Gson gson = new Gson();
String jsonStr = gson.toJson(employee);
System.out.println(jsonStr);
System.out.println("====================================================");
/*转换对象数组*/
EmployeeDaoImpl employeeDao = new EmployeeDaoImpl();
List<Employee> emps = employeeDao.getEmployee();
String strs = gson.toJson(emps);
System.out.println(strs);
}
JQuery asynchronous request returns JSON data
java code block:
@WebServlet(name = "GetEmpsJsonStrServlet",urlPatterns = "/getJsonServlet")
public class GetEmpsJsonStrServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Gson gson = new Gson();
EmployeeDaoImpl employeeDao = new EmployeeDaoImpl();
List<Employee> emps = employeeDao.getEmployee();
/*转换成json*/
String jsonStr = gson.toJson(emps);
response.setContentType("text/html;charset=utf-8");
/*写出到页面*/
response.getWriter().println(jsonStr);
}
}
html page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>一键显示信息</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script>
$(function (){
$("#showTable").click(function (){
$.ajax({
url:"getJsonServlet",
type:"post",
dataType:"json",
success:function (data){
var str = "<tr><th>编号</th><th>姓名</th><th>年龄</th>" +
"<th>部门编号</th><th>部门名称</th><th>部门地址</th></tr>";
for(var i = 0; i < data.length; ++i){
var emp = data[i];
str += "<tr align='center'><td>"+emp.id+
"</td><td>"+emp.name+"</td><td>"+emp.age+"</td><td>"+emp.dept_id+
"</td><td>"+emp.department.dep_name+"</td><td>"+emp.department.dep_location +
"</td></tr>";
}
$("#empsTable").html(str);
}
})
})
})
</script>
</head>
<body>
<h1 align="center">员工信息表</h1>
<h1 align="center"><input id="showTable" type="button" value="点击获取员工信息" align="center"></h1>
<table id="empsTable" align="center" width="70%" border="1px" cellspacing="0px">
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
<th>部门编号</th>
<th>部门名称</th>
<th>部门地址</th>
</tr>
</table>
</body>
</html>
After clicking the button: