利用json实现数据传输

Posted Claricre

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了利用json实现数据传输相关的知识,希望对你有一定的参考价值。

  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实现数据传输的主要内容,如果未能解决你的问题,请参考以下文章

Notepad++编辑器——Verilog代码片段直接编译

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

Swift新async/await并发中利用Task防止指定代码片段执行的数据竞争(Data Race)问题

如何从片段中的 JSON 响应中的对象获取数据

将 JSON 字符串从片段传递到适配器的问题

利用json实现数据传输