---
title: "@ResponseBody把返回的对象自动拼成JSON"
author: "liyonghui160com"
date: "2014-11-26T15:19:18Z"
tags: []
categories: ["互联网"]
slug: "responsebody-json"
draft: false
lastmod: "2014-11-26T15:19:18Z"
id: 2160895
url: "https://liyonghui160com.iteye.com/blog/2160895"
---

使用@ResponseBody，把要返回的对象自动拼成JSON的格式返回  
当然，需要加入几个jackson的包，这里加入了：  
jackson-core-2.1.2.jar、jackson-annotations-2.1.2.jar、jackson-databind-2.1.2.jar  
n测试使用的Controller的方法：

```
@RequestMapping(value = "/hello")
@ResponseBody
public UserModel handleRequest(@RequestBody String reqBody, UserModel um) {
System.out.println("the reqBody="+reqBody);
um.setName(um.getName()+",server");
return um;
}
```

   
   
测试使用的页面

```
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<script language="javascript" src="/mvcexample/static/js/jquery-1.3.2.min.js"></script>
<script language="javascript">
$().ready(function(){
$.getJSON('/mvcexample/hello',{uuid:'1',name:'test'},function(data){
alert(data.uuid+" , "+data.name);
});
});
</script>
```

 

去测试看看吧，可以看到Controller的方法直接返回一个um对象，但是 @ResponseBody会把这个对象自动变成json格式的，再传回客户端，非常方便。

当然， @ResponseBody也支持集合对象自动变成json格式，比如：  
测试使用的Controller方法

```
@RequestMapping(value = "/hello")
@ResponseBody
public List<UserModel> handleRequest(@RequestBody String reqBody, UserModel um) {
System.out.println("the reqBody="+reqBody);
um.setName(um.getName()+",server");
List<UserModel> list = new ArrayList<UserModel>();
list.add(um);
UserModel um2 = new UserModel();
um2.setUuid("22");
um2.setName("222");
list.add(um2);
return list;
}
```

 

n测试使用的页面

```
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
<script language="javascript" src="/mvcexample/static/js/jquery-1.3.2.min.js"></script>
<script language="javascript">
$().ready(function(){
$.getJSON('/mvcexample/hello',{uuid:'1',name:'test'},function(data){
$.each(data,function(index,v){
alert("tr="+v.uuid+",v="+v.name);
});
});
});
</script> 
```