[英]Springboot API returns empty response
I built a simple Springboot API which is hooked up to a H2 db that contains some test data. 我构建了一个简单的Springboot API,该API连接到包含一些测试数据的H2数据库。 However when I hit the API endpoint I get an empty response.
但是,当我点击API端点时,我得到一个空响应。
[{}]
When I debug my application the user object that is returned by the controller contains the user I am expecting. 当我调试应用程序时,控制器返回的用户对象包含我期望的用户。
UserController.java UserController.java
@RestController
@RequestMapping("api/user")
public class UserController {
private UserService userService;
public UserController(@Autowired UserService userService){
this.userService = userService;
}
@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public Set<User> getAllUsers(){
final Set<User> users = userService.getAllUsers();
return users;
}
}
UserRepo.java UserRepo.java
public interface UserRepository extends CrudRepository<User, Long> {
@Query("SELECT usr from User usr")
Set<User> getAllUsers();
}
UserService.java UserService.java
public interface UserService {
Set<User> getAllUsers();
}
UserServiceImpl.java UserServiceImpl.java
@Service
public class UserServiceImpl implements UserService {
private final UserRepository repository;
public UserServiceImpl(@Autowired UserRepository userRepository){
this.repository = userRepository;
}
@Override
public Set<User> getAllUsers(){
final Set<User> users = repository.getAllUsers();
return users;
}
}
User.java User.java
@Entity
@Getter
public class User {
@Id
private Long id;
private String username;
private String firstname;
private String lastname;
private String email;
private String role;
private String premium;
}
This was a rather strange issue of which I am still unable to say which. 这是一个相当奇怪的问题,我仍然无法说出哪个。 However, removing lombok's
@getter
and @setter
annotations then implementing traditional ones fixed this issue. 但是,删除
@getter
的@getter
和@setter
批注,然后实施传统的批注,可以解决此问题。
You'll have to set the class members of User
public to allow jackson serialise them, ie, 您必须将
User
的类成员设置为public,以允许jackson序列化它们,即,
// User.java
@Entity
public class User {
@Id
public Long id;
public String username;
public String firstname;
public String lastname;
public String email;
public String role;
public String premium;
}
Note : if you'd like to not serialise a field, use @JsonIgnore
instead of setting it as private, eg, 注意 :如果您不想序列化字段,请使用
@JsonIgnore
而不是将其设置为私有,例如,
@Entity
public class User {
...
@JsonIgnore
public String role;
...
}
Just remove final and change Set to List as well. 只需删除final并更改“设置为列表”即可。 and you really don`t need to do like this:
而且您真的不需要这样做:
public UserController(@Autowired UserService userService)
Just remove this method and add Autowired
up to userService
filed. 只需删除此方法,然后将
Autowired
添加到userService
。 Because final object can`t be cast to json string. 因为最终对象不能转换为json字符串。 remove this as well:
也删除此:
produces = MediaType.APPLICATION_JSON_VALUE</h3>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.