接收、返回Json Day8 2018-11-26
2018-11-26 本文已影响0人
Ernest_Chou
4. json数据转换
4.1 Jackson接收JSON格式数据
4.1.1 pom.xml
- 添加Jackson支持
<!-- jackson -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.7</version>
</dependency>
4.1.2 springmvc-config.xml添加配置:
<!-- 设置配置方案 自动注册RequestMappingHandlerMapping、RequestMappingHandlerAdapter-->
<mvc:annotation-driven/>
<!-- 使用默认的Servlet来响应静态文件 -->
<mvc:default-servlet-handler/>
- 说明
<!-- 处理器映射器、处理器适配器不配置时,spring会使用默认配置处理请求 -->
<!-- 主动配置,@Controller分发请求必须,并提供数据绑定支持@NumberFormannotation、@DataTime、@Valid、读写xml(JAXB)、读写json(默认Jackson) -->
<!-- 配置annotation类型的处理映射器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<!-- 配置annotation类型的处理器适配器 -->
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/>
-
web.xml中配置的
DispatchServlet
会拦截所有请求url,而引入jsundefined<script type="text/javascript" src="../include/js/json3.min.js"></script>
将所有“/”看成请求路径,会报404。当加上默认配置的Servlet时,Servlet找不到它时会去找静态的内容。
4.1.3 @Controller
@Controller
@RequestMapping(value="/testRequestBody")
public class RequestBodyTestController {
private static final Log logger = LogFactory.getLog(RequestBodyTestController.class);
//@RequestBody 根据json数据,转换成对于的Object
@RequestMapping(value="/setJackson")
public void setJackson(@RequestBody User user,HttpServletResponse response) throws IOException{
//ObjectMapper 类是Jackson库的主要类。提供将Java对象转换成对于的JSON格式数据的功能
ObjectMapper mapper = new ObjectMapper();
//将User对象转换为json输出
logger.info(mapper.writeValueAsString(user));
user.setUserName("测试JSON转换");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(mapper.writeValueAsString(user));
}
}
4.1.4 jsp
<body>
登录名:<span id="loginName"></span><br>
密码:<span id="password"></span><br>
用户名:<span id="userName"></span><br>
</body>
<script type="text/javascript" src="../include/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="../include/js/json3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testSetJackson();
});
function testSetJackson(){
$.ajax("${pageContext.request.contextPath}/testRequestBody/setJackson",
{
dataType:"json",
type:"post",
contentType:"application/json",
data:JSON.stringify({password:1,loginName:"spring MVC 企业应用实践setJackson"}),
async:true,
success:function(data){
console.log(data),
$("#loginName").html(data.loginName);
$("#password").html(data.password);
$("#userName").html(data.userName);
},
error:function(){
alert("数据发送失败!");
}
});
}
</script>
4.2 FastJson接收JSON格式数据
4.3.1 pom.xml
- 添加Jackson支持
<!--添加fastjson支持 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.53</version>
</dependency>
4.1.2 springmvc-config.xml添加配置:
- 使用第三方的fastjson处理json数据,需要配置HTTPMessageConverter
<!-- 使用默认的Servlet来响应静态文件 -->
<mvc:default-servlet-handler/>
<!-- 设置配置方案 -->
<mvc:annotation-driven>
<!-- 设置不适用默认的消息转换器 -->
<mvc:message-converters register-defaults="false">
<!-- 配置spring的转换器 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.support.AllEncompassingFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<!-- 配置fastjson中实现HTTPMessageConverter接口的转换器 -->
<!-- FastJsonHttpMessageConverter是fastjson中实现了HTTPMessageConverter接口的类 -->
<bean id="fastJsonHttpMessageConverter" class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型:返回contentType -->
<property name="supportedMediaTypes">
<list>
<!-- 一定要先写text/html,不然IE下会出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
4.1.3 @Controller
@Controller
@RequestMapping(value="/testRequestBody")
public class RequestBodyTestController {
private static final Log logger = LogFactory.getLog(RequestBodyTestController.class);
//@RequestBody 根据json数据,转换成对于的Object
@RequestMapping(value="/setFastjson")
public void setFastjson(@RequestBody User user,HttpServletResponse response) throws IOException{
//JSONObject-lib是一个beans,collection是,maps,javaarrays和xml、json互相转换的包
//使用JSONObject将User对象转换为json输出
logger.info(JSONObject.toJSONString(user));
user.setUserName("测试Fastjson转换");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().println(JSONObject.toJSONString(user));
}
}
4.1.4 jsp
<body>
登录名:<span id="loginName"></span><br>
密码:<span id="password"></span><br>
用户名:<span id="userName"></span><br>
</body>
<script type="text/javascript" src="../include/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="../include/js/json3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testSetFastjson();
});
function testSetFastjson(){
$.ajax("${pageContext.request.contextPath}/testRequestBody/setFastjson",
{
dataType:"json",
type:"post",
contentType:"application/json",
data:JSON.stringify({password:1,loginName:"spring MVC 企业应用实践setFastjson"}),
async:true,
success:function(data){
console.log(data),
$("#loginName").html(data.loginName);
$("#password").html(data.password);
$("#userName").html(data.userName);
},
error:function(){
alert("数据发送失败!");
}
});
}
</script>
4.3 Jackson返回JSON格式数据
4.3.1 pom.xml
- 同 4.1.1
4.3.2 springmvc-config.xml配置
- 同4.1.2
4.3.3 @Controller
@Controller
@RequestMapping(value="/testResponseBody")
public class ResponseBodyTestController {
@RequestMapping(value="/getJackson")
@ResponseBody//将集合数据转换为json格式并将其返回客户端
public Object getJackson() {
List<User> list = new ArrayList<User>();
list.add(new User("shi_yue", "1Jackson", "石悦"));
list.add(new User("shi_lili", "2Jackson", "石丽丽"));
return list;
}
}
4.3.4 jsp
<body>
<table id="userTable" border="1" style="border-collapse: collapse;">
<tr>
<th>登录名</th>
<th>密码</th>
<th>用户名</th>
</tr>
</table>
</body>
<script type="text/javascript" src="../include/js/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="../include/js/json3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
testResponeBody();
});
function testResponeBody(){
$.post("${pageContext.request.contextPath}/testResponseBody/getJackson",null,
function(data){
$.each(data,function(){
var tr = $("<tr align='center' />");
$("<td/>").html(this.loginName).appendTo(tr);
$("<td/>").html(this.password).appendTo(tr);
$("<td/>").html(this.userName).appendTo(tr);
$("#userTable").append(tr);
})
},
"json");
}
</script>
4.4 自定义HttpMessageConverter返回JSON格式数据
4.4.1 pom.xml
- 同 4.2.1
4.4.2 springmvc-config.xml配置
- 同4.2.2
4.4.3 @Controller
- 同 4.3.3
4.4.4 @jsp
- 同 4.3.4