spring boot最新教程(四):返回json数据以及集成fastjson的使用

一  利用spring boot自带的包Jackson来解析json数据

我们在编写接口的时候,时常会有需求返回json数据,那么在spring boot应该怎么操作呢?主要是在class中加入注解@RestController。关于@RestController请参考我的博文[http://blog.csdn.net/wx5040257/article/details/79451449]

================pom.xml==================

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.wx</groupId>
	<artifactId>springboot03</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.5.2.RELEASE</version>
	</parent>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.apache.tomcat.embed</groupId>
			<artifactId>tomcat-embed-jasper</artifactId>
			<scope>provided</scope>
		</dependency>
		<!-- jstl标签库 -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<!--alibaba fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.32</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<!-- java编译插件 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
					<encoding>UTF-8</encoding>
				</configuration>
			</plugin>
			<!-- 如果你不想用maven命令运行spring boot可以不用作此配置 -->
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>

	</build>
</project>

全局配置文件

==============application.properties====================

server.port=8080
spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp
server.servlet-path=*.php
#修改了jsp,servlet不用重新启动
server.jsp-servlet.init-parameters.development=true

控制器JsonCotroller

==============JsonCotroller================

package com.wx.controlers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.wx.entitys.UserEntity;

@RestController
public class JsonController {
	@RequestMapping("/getString")
    public String hello(){
        return "Hello";
    }
	
	@RequestMapping("/getEntity.php")
    public UserEntity showEntity(){
        UserEntity user=new UserEntity();
        user.setUserId(100);
        user.setUserName("麻子");
        user.setPassWord("123");
        user.setEmail("mazi@qq.com");
        return user;
    }
	
	@RequestMapping("/getList.php")
    public List<UserEntity> showList(){
		List<UserEntity> userList=new ArrayList<UserEntity>();
        UserEntity user=new UserEntity();
        user.setUserId(100);
        user.setUserName("麻子");
        user.setPassWord("123");
        user.setEmail("mazi@qq.com");
        userList.add(user);
        user=new UserEntity();
        user.setUserId(101);
        user.setUserName("小丽");
        user.setPassWord("321");
        user.setEmail("xiaoli@qq.com");
        userList.add(user);
        return userList;
    }
}

启动程序,在地址栏输入

http://localhost:8080/getEntity.php,得到如下结果


输入http://localhost:8080/getList.php,得到


注意得到的直接是json对象,而不是json字符串

展示在页码上

==================ShowJsonResult.jsp============

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="scheme" value="${pageContext.request.scheme}"></c:set>
<c:set var="serverName" value="${pageContext.request.serverName}"></c:set>
<c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${contextPath}/"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="${basePath}">
    <title>展示一个用户数据</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
<script type="text/javascript" src="js/jquery.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(e){
	$("#clickOne").click(function(e){
		$.post("getEntity.php","",function(result){
			//得到的结果直接是json对象,都不用再转换了
		    var innerStr="<h3>"+result.userId+","+result.userName
		        +","+result.email+"</h3>";
			$("#showOne").html(innerStr);
		});
	});
	
	$("#clickMany").click(function(e){
		$.post("getList.php","",function(result){
			var innerStr="";
			for(var i=0;i<result.length;i++){
				innerStr=innerStr+result[i].userId+","+result[i].userName+","
				    +result[i].email+"<br/>";
			}
			innerStr="<h3>"+innerStr+"</h3>";
			$("#showMany").html(innerStr);
		});
	});
});
</script>   
<body>

<h1>输出json里面的数据</h1>
<div><input type="button" id="clickOne" value="展示一个对象"/><br/>
    <div id="showOne"></div>
</div>
<div><input type="button" id="clickMany" value="展示一个数组"/><br/>
    <div id="showMany"></div>
</div>
</body>
</html>

页码结果如图所示:


二  利用阿里巴巴的fastjson来解析json数据

导入依赖

<!--alibaba fastjson -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.32</version>
		</dependency>

编写控制器类

================FastJsonController.java===================

package com.wx.controlers;

import java.util.ArrayList;
import java.util.List;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSONObject;
import com.wx.entitys.UserEntity;

@RestController
public class FastJsonController {
	
	@RequestMapping("/getFastEntity.php")
    public String showEntity(){
        UserEntity user=new UserEntity();
        user.setUserId(100);
        user.setUserName("麻子");
        user.setPassWord("123");
        user.setEmail("mazi@qq.com");
        return JSONObject.toJSONString(user);
    }
	
	@RequestMapping("/getFastList.php")
    public String showList(){
		List<UserEntity> userList=new ArrayList<UserEntity>();
        UserEntity user=new UserEntity();
        user.setUserId(100);
        user.setUserName("麻子");
        user.setPassWord("123");
        user.setEmail("mazi@qq.com");
        userList.add(user);
        user=new UserEntity();
        user.setUserId(101);
        user.setUserName("小丽");
        user.setPassWord("321");
        user.setEmail("xiaoli@qq.com");
        userList.add(user);
        return JSONObject.toJSONString(userList);
    }
}

注意看返回值,无法直接像jackson一样直接得到json对象,这里是返回的json字符串,需要在页面中转换!

页码代码

===================ShowFastJsonResult.jsp===============

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<c:set var="scheme" value="${pageContext.request.scheme}"></c:set>
<c:set var="serverName" value="${pageContext.request.serverName}"></c:set>
<c:set var="serverPort" value="${pageContext.request.serverPort}"></c:set>
<c:set var="contextPath" value="${pageContext.request.contextPath}"></c:set>
<c:set var="basePath" value="${scheme}://${serverName}:${serverPort}${contextPath}/"></c:set>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="${basePath}">
    <title>展示一个用户数据</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head>
<script type="text/javascript" src="js/jquery.min.js"></script>  
<script type="text/javascript">
$(document).ready(function(e){
	$("#clickOne").click(function(e){
		$.post("getFastEntity.php","",function(result){
			//把json字符串转换成json对象
			var jsonObj=$.parseJSON(result);
		    var innerStr="<h3>"+jsonObj.userId+","+jsonObj.userName
		        +","+jsonObj.email+"</h3>";
			$("#showOne").html(innerStr);
		});
	});
	
	$("#clickMany").click(function(e){
		$.post("getFastList.php","",function(result){
			//把json字符串转换成json对象
			var jsonObj=$.parseJSON(result);
			var innerStr="";
			for(var i=0;i<jsonObj.length;i++){
				innerStr=innerStr+jsonObj[i].userId+","+jsonObj[i].userName+","
				    +jsonObj[i].email+"<br/>";
			}
			innerStr="<h3>"+innerStr+"</h3>";
			$("#showMany").html(innerStr);
			
		});
	});
});
</script>   
<body>

<h1>输出json里面的数据</h1>
<div><input type="button" id="clickOne" value="展示一个对象"/><br/>
    <div id="showOne"></div>
</div>
<div><input type="button" id="clickMany" value="展示一个数组"/><br/>
    <div id="showMany"></div>
</div>
</body>
</html>

点击两个按钮得到的结果与前面一致!注意这里要调用

var jsonObj=$.parseJSON(result);

把json串转换成json对象!



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

御前两把刀刀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值