利用json實現資料轉送

來源:互聯網
上載者:User

標籤:標記法   利用   tca   length   bsp   ext   asc   turn   get   

  JSON:JavaScript 物件標記法(JavaScript Object Notation)。

  JSON 是儲存和交換文本資訊的文法。類似 XML。

  JSON 比 XML 更小、更快,更易解析。

    JSON 使用 JavaScript 文法來描述資料對象,但是 JSON 仍然獨立於語言和平台。JSON 解析器和 JSON 庫支援許多不同的程式設計語言。

使用json來傳輸單個資料和數組

建立一個資料層:

package com.bean;public class Dog {    private String name;    public String getName() {        return name;    }    public void setName(String name) {        this.name = name;    }    public int getAge() {        return age;    }    public void setAge(int age) {        this.age = age;    }    public String getCategory() {        return category;    }    public void setCategory(String category) {        this.category = category;    }    private int age;    private String category;}

實現單個資料轉送時:

package com.servlet;import java.io.IOException;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 org.json.JSONObject;import com.bean.Dog;/** * Servlet implementation class Testjson1 */@WebServlet("/testjson1")public class Testjson1 extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public Testjson1() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        //摸擬從資料庫中查詢        Dog d = new Dog();        d.setName("阿黃");        d.setAge(2);        d.setCategory("哈士奇");                JSONObject obj = new JSONObject();        obj.put("name", d.getName());        obj.put("age", d.getAge());        obj.put("category", d.getCategory());                JSONObject object = new JSONObject();        object.put("dog1", obj);        response.getWriter().append(object.toString());    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!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=ISO-8859-1"><title>Insert title here</title><script type="text/javascript"src="js/jquery-1.11.1.min.js"></script><script type="text/javascript">$(document).ready(function(){    $("#d1").click(function(){        $.ajax({            url:"testjson1",            data:{},            type:"POST",            dataType:"JSON",            success:function(httpdata){                $("#d2").append("<p>"+httpdata.dog1.name+"</p>");                $("#d2").append("<p>"+httpdata.dog1.age+"</p>");                $("#d2").append("<p>"+httpdata.dog1.category+"</p>");                            }        });    });});</script></head><body><div id="d1">123123123</div><div id="d2"></div></body></html>

效果如下:

傳輸一組資料時:

package com.servlet;import java.io.IOException;import java.util.ArrayList;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 org.json.JSONArray;import org.json.JSONObject;import com.bean.Dog;/** * Servlet implementation class Testjson2 */@WebServlet("/testjson2")public class Testjson2 extends HttpServlet {    private static final long serialVersionUID = 1L;           /**     * @see HttpServlet#HttpServlet()     */    public Testjson2() {        super();        // TODO Auto-generated constructor stub    }    /**     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)     */    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        request.setCharacterEncoding("utf-8");        response.setCharacterEncoding("utf-8");        Dog d1 = new Dog();        d1.setName("狗1");        d1.setAge(1);        d1.setCategory("品種1");        Dog d2 = new Dog();        d2.setName("狗2");        d2.setAge(2);        d2.setCategory("品種2");        Dog d3 = new Dog();        d3.setName("狗3");        d3.setAge(3);        d3.setCategory("品種3");                ArrayList<Dog> list = new ArrayList<Dog>();        list.add(d1);        list.add(d2);        list.add(d3);                        JSONArray arr = new JSONArray();                for(Dog d:list){                        //System.out.println(d.getName());            JSONObject temp = new JSONObject();            temp.put("name", d.getName());            temp.put("age", d.getAge());            temp.put("category", d.getCategory());            arr.put(temp);        }        JSONObject object = new JSONObject();        object.put("dog1", arr);                //response.getWriter().append(obj.toString());        response.getWriter().append(object.toString());    }    /**     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)     */    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // TODO Auto-generated method stub        doGet(request, response);    }}

 

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"    pageEncoding="ISO-8859-1"%><!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=ISO-8859-1"><title>Insert title here</title><script type="text/javascript"src="js/jquery-1.11.1.min.js"></script><script type="text/javascript">$(document).ready(function(){    $("#d1").click(function(){        $.ajax({            url:"testjson2",            data:{},            type:"POST",            dataType:"JSON",            success:function(httpdata){                                                                for(var i=0;i<httpdata.dog1.length;i++){                                                            $("#d2").append("<p>"+httpdata.dog1[i].name+"</p>");                    $("#d2").append("<p>"+httpdata.dog1[i].age+"</p>");                    $("#d2").append("<p>"+httpdata.dog1[i].category+"</p>");                                    }                                            }        });    });});</script></head><body><div id="d1">123123123</div><div id="d2"></div></body></html>

實現效果如下:

 

利用json實現資料轉送

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.