springmvc转换json数据

1接受JSON格式数据:

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>测试接收JSON格式的数据</title>
    <%--<link rel="stylesheet" href="${pageContext.request.contextPath}/js/json2.js" />--%>
    <script type="text/javascript" src="../js/json2.js"></script>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            testRequestBody();
        });
        function testRequestBody(){
            $.ajax("${pageContext.request.contextPath}/json/testRequestBody",// 发送请求的URL字符串。
                {
                    dataType : "json", // 预期服务器返回的数据类型。
                    type : "post", //  请求方式 POST或GET
                    contentType:"application/json", //  发送信息至服务器时的内容编码类型 ,表示发送的内容是json类型
                    // 发送到服务器的数据。
                    data:JSON.stringify({id : 1, name : "spring",author:"jkf"}),
                    async:  true , // 默认设置下,所有请求均为异步请求。如果设置为false,则发送同步请求
                    // 请求成功后的回调函数。
                    success :function(data){
                        console.log(data);
                        $("#id").html(data.id);
                        $("#name").html(data.name);
                        $("#author").html(data.author);
                    },
                    // 请求出错时调用的函数
                    error:function(){
                        alert("数据发送失败");
                    }
                });
        }
    </script>
</head>
<body>
编号:<span id="id"></span><br>
书名:<span id="name"></span><br>
作者:<span id="author"></span><br>
</body>
</html>

package controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import model.Book;
import model.Car;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Controller
@RequestMapping("/json")
public class BookController {

    @RequestMapping("/testRequestBody")
    public void setJosn(@RequestBody Book book, HttpServletResponse response) throws Exception{
        String s = JSONObject.toJSONString(book);//fastjson接受json数据
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(JSONObject.toJSONString(book));
    }

  
}

2.返回JSON格式的数据

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2017/12/18 0018
  Time: 10:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>测试返回Json格式的数据</title>
    <script type="text/javascript" src="/js/json2.js"></script>
    <script src="http://libs.baidu.com/jquery/1.9.1/jquery.min.js"></script>

    <script type="text/javascript">
        $(document).ready(function(){
            testResponseBody();
        });
        function testResponseBody(){
            $.post("${packContext.request.contextPath}/json/testResponseBody",null,function(data){ //发送请求到具体的控制器,@ResponseBody返回一个json数据
                $.each(data,function(){
                    var tr = $("<tr align='center'/>")
                    $("<td/>").html(this.id).appendTo(tr);
                    $("<td/>").html(this.name).appendTo(tr);
                    $("<td/>").html(this.author).appendTo(tr);
                    $("#booktable").append(tr);
                })
            },"json")
        }
    </script>
</head>
<body>
<table id="booktable" border="1" style="border-collapse: collapse">
    <tr align="center">
        <th>编号</th>
        <th>书名</th>
        <th>作者</th>
    </tr>
</table>
</body>
</html>

package controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.util.JSONPObject;
import model.Book;
import model.Car;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

@Controller
@RequestMapping("/json")
public class BookController {



    @RequestMapping("/testResponseBody")
    public @ResponseBody Object getJson(){
        List<Book> books = new ArrayList<Book>();
        books.add(new Book("1","spring+mybatis企业应用实战","肖吉文"));
        books.add(new Book("2","Java疯狂讲义","李刚"));
        return books;
    }
}

json需要的pom.xml

  <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.39</version>
    </dependency>



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值