处理JSON

JSON:本质是一个特殊的JS内置对象,或者一种JS类型。作为数据交互的格式存在。可以是对象、数组、数字、字符串或者三个字面值(false、null、true)中的一个。值中的字面值中的英文必须使用小写。

1、JSON有两种格式:

  1)JSON对象:{key: value, key:value,....}。 ({ } 花括号表示JSON对象)

  2)JSON数组:[value1,value2,...],每个value都是一个JSON对象。([ ]方括号表示JSON数组)

2、JSON对象的解析方式:

  1)对象.key;

  2) JSON数组通过for循环遍历

3、Java对象转换为JSON

  1)Bean和map----->json对象

  2)List---->json数组


例如需要从Java传输User对象到JavaScript中。User: name:sun,password=1234,age=90.

两种解决方案:

1)XML先将JAVA中的数据放到一个xml中,然后再传送到JavaScript中解析。但是xml文件的读写是很复杂的。xml可扩展标示语言,通过标签描述数据名称,标签内容描述数据内容。但是通过xml描述数据代码量很大。

<userInfo>
  <user>
    <name>sun</name>
    ...
  </user>

  <user>....</user>
</userInfo>

2)JSON创建json对象:Var data={name:sun, passwprd:1234,age:90}。键值对,直接通过 data.name就可以获取属性值。


SpringMVC默认使用 jackson。

405:客户端发送到服务器端的请求方式不匹配

406:服务器端发送客户端的数据,客户端不能处理

400:客户端发送的请求服务器端不能处理


SpringMVC使用JSON步骤

1、加入jar包 下载🔗

  jackson-annotations-2.1.5.jar

  jackson-core-2.1.5.jar

  jackson-databind-2.1.5.jar

2、在springMVC的配置文件中开启MVC驱动<mvc:annotation-driven />

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

<context:component-scan base-package="com.spring"></context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/view/"></property>
    <property name="suffix" value=".jsp"></property>
</bean>

<mvc:annotation-driven></mvc:annotation-driven>


</beans>

3、在处理ajax请求的方法上加上注解@ResponseBody

4、将要转换为json且响应到客户端的数据,直接作为该方法的返回值返回return

package com.spring.controller;

import java.util.Collection;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.spring.bean.Employee;
import com.spring.dao.EmployeeDao;

@Controller
public class TestJsonController {
    
    @Autowired
    private EmployeeDao employeeDao;
    
    
    @RequestMapping(value="/testJson")
    @ResponseBody
    public Collection<Employee> test()
    {
        Collection<Employee> emps = employeeDao.getAll();
        return emps;
    }


}

 


Ajax异步请求显示数据:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<link rel="stylesheet" href="${pageContext.servletContext.contextPath }/css/index_like.css"/>
<script type="text/javascript" src="${pageContext.servletContext.contextPath }/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btn").click(function () {
            $.ajax({
                url:"testJson",
                type:"POST",
                dataType:"json",
                success:function (msg){
                    /*
                        [
                            {"id":1001,"lastName":"E-AA","email":"aa@163.com","gender":1,"department":{"id":101,"departmentName":"D-AA"}},
                            {"id":1002,"lastName":"E-BB","email":"bb@163.com","gender":1,"department":{"id":102,"departmentName":"D-BB"}},
                            {"id":1003,"lastName":"E-CC","email":"cc@163.com","gender":0,"department":{"id":103,"departmentName":"D-CC"}},
                            {"id":1004,"lastName":"E-DD","email":"dd@163.com","gender":0,"department":{"id":104,"departmentName":"D-DD"}},
                            {"id":1005,"lastName":"E-EE","email":"ee@163.com","gender":1,"department":{"id":105,"departmentName":"D-EE"}}
                        ]
                    */
                    /* for(var i in msg){
                        var emp = msg[i];
                        alert("id="+emp.id+",lastName="+emp.lastName+",departmentName="+emp.department.departmentName);
                    } */
                    //第一种实现方式
                    /* var tb = "<table>";
                    tb += "<tr><th>id</th><th>lastName</th><th>email</th><th>gender</th><th>departmentName</th></tr>";
                    for(var i in msg){
                        var emp = msg[i];
                        tb += "<tr><td>"+emp.id+"</td><td>"+emp.lastName+"</td><td>"+emp.email+"</td><td>"+emp.gender+"</td><td>"+emp.department.departmentName+"</td></tr>";
                    }
                    tb += "</table>";
                    $("body").append(tb); */
                    //第二种实现方式
                    $("body").append("<table></table>");
                    $("table").append("<tr><th>id</th><th>lastName</th><th>email</th><th>gender</th><th>departmentName</th></tr>");
                    for(var i in msg){
                        var emp = msg[i];
                        $("table").append("<tr><td>"+emp.id+"</td><td>"+emp.lastName+"</td><td>"+emp.email+"</td><td>"+emp.gender+"</td><td>"+emp.department.departmentName+"</td></tr>");
                    }
                }
            });
        });
    });
</script>
</head>
<body>
    
    <input id="btn" type="button" value="测试ajax" />

    <a href="testJson">测试Json</a>

</body>
</html>

 

posted @ 2020-05-22 11:16  kkzhang  阅读(322)  评论(0编辑  收藏  举报