Json技术

JSON语法是一种用于传输和生成数据的协定,很类似于C家族的语言,所以很容易被C家族的语言所解析。
对象:对象包含再{}之间
属性:采用Key-Value对来表示。属性之间使用逗号分开。  string : value 
数组:数组存放再[]之间   [ elements ] 
元素:元素之间用逗号分开
值:值可以是字符串,数字,对象,数组,true,false,null

json的官方文档:http://www.json.org/json-zh.html

JSON的优点
轻量级的数据交换格式

人们读写更加容易

易于机器的解析和生成

能够通过JavaScript中eval()函数解析JSON

JSON支持多语言。包括:ActionScript, C, C#, ColdFusion, E, Java, JavaScript, ML, Objective CAML, Perl, PHP, Python, Rebol, Ruby, and Lua.

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
<!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>ajax处理json数据演示示例</title>
        <script type="text/javascript">
             
                     
            function ask4(){
                //1创建ajax对象
                var xhr=null;
                if(window.XMLHttpRequest){//高版本IE,火狐等
                    xhr = new XMLHttpRequest();
                }else{//低版本IE
                    xhr = new ActiveXObject("Microft.XMLHttp");
                }
                //2请求地址
                var url = "<c:url value='/JsonServlet3'/>"; //post方式,请求参数在 send()方法的实参
                //3设置访问方式
                xhr.open("POST", url, true);
                
                //4设置访问成功返回后的操作
                xhr.onreadystatechange = function(){
                    if(xhr.readyState==4){
                        if(xhr.status==200){
                            var txt = xhr.responseText;
                            //alert(txt);
                            ///////////解析后台返回的json串/////////////
                            //js中的eval()方法的功能: 校验参数文本串符合js中哪一种数据类型,并把其转换成对应类型的对象---json
                            var users = eval( "("+txt+")" ); //得到一个json对象
                            for(var i=0; i<users.length; i++){
                                alert(users[i].id+","+users[i].name+","+users[i].age)
                            }                        
                        }
                    }
                };
                
                xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded" );
                //5发送
                xhr.send(null);
            }
        </script>
    </head>
    <body>
 
        <input type="button" onclick="ask4();" value="ajax请求后台数据(后台--用fastjson工具封装json的方式)">  <br/>
        
    </body>
</html>
package cn.hncu.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import cn.hncu.domain.User;

@WebServlet("/JsonServlet3")
public class JsonServlet3 extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //按理应该调用service、dao层并从数据库中把数据读取出来,这里模拟了...
        List<User> users = new ArrayList<User>();
        users.add( new User("U001","Jack",22));
        users.add( new User("U010","张三",12));
        users.add( new User("U002","Rose",23));
        request.setAttribute("users", users);

        //利用fastjson的工具为我们把后台的List<User>类型的数据封装成json格式串,发送前端
        //json串格式: [{name:"Jack",id:"U001",age:22},{...},{...}]
        //转List-json※※※
        String json = JSON.toJSONString(users);
        System.out.println(json);
        
        //转Map-json
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("addr", "湖南");
        map.put("id", "P001");
        map.put("sex", "男");
        map.put("age", 20);
        map.put("friend", new User("U001","Jack",22));
        String str = JSON.toJSONString(map);
        System.out.println(str);
        
        //发给前端
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(json);
    }
}
//利用apache的工具为我们把后台的List<User>类型的数据封装成json格式串,发送前端
        //json串格式: [{name:"Jack",id:"U001",age:22},{...},{...}]
        //转List-json
        JSONArray jsonObj=JSONArray.fromObject(users);//转换List的方法
        String json = jsonObj.toString();
        System.out.println(json);
        
        //转Map-json
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("addr", "湖南");
        map.put("id", "P001");
        map.put("sex", "男");
        map.put("age", 20);
        map.put("friend", new User("U001","Jack",22));
        JSONObject obj = JSONObject.fromObject(map);
        System.out.println(obj.toString());
        
        //发给前端
        response.setCharacterEncoding("utf-8");
        response.getWriter().print(json);


这里还可以采用apache中工具把数据封装成json字符串,还可以
在后台把我们的List<User>类型的数据手动封装成json格式串,发送前端

//json串格式: [{name:"Jack",id:"U001",age:22},{...},{...}]


 这里使用Json工具的时候要导包----->fastjson-1.1.17.jar----->json-lib-2.3-jdk15.jar

原文地址:https://www.cnblogs.com/1314wamm/p/6516726.html