有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何更改存储库生成的json数组的格式。弹簧靴中的findAll()

我想将此json列表更改为另一种格式,方法是在列表前加上“data”一词,并将其包含在括号中,如我所写的示例中所示 我使用的rest控制器

   @CrossOrigin(origins = "http://localhost:8080")
  @GetMapping("/users")
  public List<User> getAllUsers() {
    return userRepository.findAll();
  }

回答是这样的

    [
            {
                "id": 1,
                "firstName": "test",
                "lastName": "test",
                "email": "tt",
                "createdAt": null,
                "createdBy": "12",
                "updatedAt": null,
                "updatedBy": "12"
            },
            {
                "id": 2,
                "firstName": "test",
                "lastName": "test",
                "email": "tt",
                "createdAt": null,
                "createdBy": "12",
                "updatedAt": null,
                "updatedBy": "12"
            }
        ]

我想这样做

{
    "data": [
        {
            "id": 1,
            "firstName": "test",
            "lastName": "test",
            "email": "tt",
            "createdAt": null,
            "createdBy": "12",
            "updatedAt": null,
            "updatedBy": "12"
        },
        {
            "id": 2,
            "firstName": "test",
            "lastName": "test",
            "email": "tt",
            "createdAt": null,
            "createdBy": "12",
            "updatedAt": null,
            "updatedBy": "12"
        }
    ]
    }
 

共 (1) 个答案

  1. # 1 楼答案

    可以使用“数据属性”创建另一个模型类

    public class UserData {
    
       private List<User> data
       // getters and setters
    
      }
    

    然后更改控制器中的返回类型

     @CrossOrigin(origins = "http://localhost:8080")
     @GetMapping("/users")
     public UserData getAllUsers() {
         List<User> users = userRepository.findAll();
         return new UserData(users);
      }
    

    或者,如果不想创建其他模型,可以使用Map<String, List<User>>

      @CrossOrigin(origins = "http://localhost:8080")
      @GetMapping("/users")
      public Map<String, List<User>> getAllUsers() {
      List<User> users = userRepository.findAll();
      return Collections.singletonMap("data",users);
    }