在Spring MVC中,JSON类型的数据如何交互?请按照返回实体对象、ArrayList集合、Map<String,Object>集合以及List<Map<Spring,Object>>集合举例说明
时间: 2023-11-11 19:32:20 浏览: 88
C# 集合 使用总结
在Spring MVC中,JSON类型的数据可以通过@ResponseBody注解返回到前端。
1. 返回实体对象:
```java
@RequestMapping(value = "/getEntity", method = RequestMethod.GET)
@ResponseBody
public User getEntity() {
User user = new User();
user.setId(1);
user.setName("Tom");
user.setAge(20);
return user;
}
```
2. 返回ArrayList集合:
```java
@RequestMapping(value = "/getList", method = RequestMethod.GET)
@ResponseBody
public List<User> getList() {
List<User> userList = new ArrayList<User>();
User user1 = new User();
user1.setId(1);
user1.setName("Tom");
user1.setAge(20);
userList.add(user1);
User user2 = new User();
user2.setId(2);
user2.setName("Jerry");
user2.setAge(22);
userList.add(user2);
return userList;
}
```
3. 返回Map<String,Object>集合:
```java
@RequestMapping(value = "/getMap", method = RequestMethod.GET)
@ResponseBody
public Map<String,Object> getMap() {
Map<String,Object> map = new HashMap<String,Object>();
map.put("id", 1);
map.put("name", "Tom");
map.put("age", 20);
return map;
}
```
4. 返回List<Map<String,Object>>集合:
```java
@RequestMapping(value = "/getListMap", method = RequestMethod.GET)
@ResponseBody
public List<Map<String,Object>> getListMap() {
List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
Map<String,Object> map1 = new HashMap<String,Object>();
map1.put("id", 1);
map1.put("name", "Tom");
map1.put("age", 20);
list.add(map1);
Map<String,Object> map2 = new HashMap<String,Object>();
map2.put("id", 2);
map2.put("name", "Jerry");
map2.put("age", 22);
list.add(map2);
return list;
}
```
以上就是返回不同类型的JSON数据的示例。
阅读全文