当前位置:   article > 正文

SpringBoot返回json数据_springboot注解返回的json是一个数组对象

springboot注解返回的json是一个数组对象

1、使用Spring InitialLizr快速搭建一个Spring Boot项目·

2 、新建一个实体类User

  1. /**
  2. * Created by Wsy on 2018-10-23 返回Json数据实体类
  3. */
  4. public class User {
  5. private int id;
  6. private String username;
  7. private String password;
  8. public String getPassword() {
  9. return password;
  10. }
  11. public void setPassword(String password) {
  12. this.password = password;
  13. }
  14. public String getUsername() {
  15. return username;
  16. }
  17. public void setUsername(String username) {
  18. this.username = username;
  19. }
  20. public int getId() {
  21. return id;
  22. }
  23. public void setId(int id) {
  24. this.id = id;
  25. }
  26. }

3、编写controller类

  1. package cn.within.controller;
  2. import cn.within.util.User;
  3. import org.springframework.web.bind.annotation.RequestMapping;
  4. import org.springframework.web.bind.annotation.RestController;
  5. import java.util.ArrayList;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. /**
  10. * Created by Wsy on 2018-10-23 Json返回数据的Controller
  11. */
  12. @RestController
  13. @RequestMapping("user")
  14. public class ReturnJsoncontroller {
  15. @RequestMapping("getUser")
  16. public User getUser(){
  17. User user = new User();
  18. user.setId(1);
  19. user.setUsername("chenwei");
  20. user.setPassword("1231");
  21. return user;
  22. }
  23. @RequestMapping("getUserList")
  24. public List<User> getUserList(){
  25. User user1 = new User();
  26. user1.setId(1);
  27. user1.setUsername("chenwei");
  28. user1.setPassword("123");
  29. User user2 = new User();
  30. user2.setId(2);
  31. user2.setUsername("xiaoyan");
  32. user2.setPassword("456");
  33. User user3 = new User();
  34. user3.setId(3);
  35. user3.setUsername("doudou");
  36. user3.setPassword("789");
  37. List<User> list = new ArrayList<>();
  38. list.add(user1);
  39. list.add(user2);
  40. list.add(user3);
  41. return list;
  42. }
  43. @RequestMapping("getUserMap")
  44. public Map<String,User> getUserMap(){
  45. User user1 = new User();
  46. user1.setId(1);
  47. user1.setUsername("chenwei");
  48. user1.setPassword("123");
  49. User user2 = new User();
  50. user2.setId(2);
  51. user2.setUsername("wsy");
  52. user2.setPassword("456");
  53. User user3 = new User();
  54. user3.setId(3);
  55. user3.setUsername("wei");
  56. user3.setPassword("789");
  57. Map<String,User> map = new HashMap<>();
  58. map.put("user1",user1);
  59. map.put("user2",user2);
  60. map.put("user3",user3);
  61. return map;
  62. }
  63. }

4、测试返回Json数据

浏览器输入http://localhost:8080/user/getUser

得出结果:服务器是以json数据格式返回给浏览器

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/619901
推荐阅读
相关标签
  

闽ICP备14008679号