Reputation: 83
I am building a CRUD Spring Boot Application. Following is the code snippet for Rest Controller
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public List<User> getUsers() {
List<User> allUsers = userRepository.findAll();
return allUsers;
}
}
When I make a call "/api/users", I get the following response :
[
{ },
{ },
]
User Class :
package entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "appuser")
public class User {
@Id
@GeneratedValue
private Long id;
private String fname;
private String lname;
public User(String fname, String lname) {
this.fname = fname;
this.lname = lname;
}
public User() {
}
@Override
public String toString() {
return "User [id=" + id + ", fname=" + fname + ", lname=" + lname + "]";
}
}
I expect the response in json form. How can I fix it?
Upvotes: 2
Views: 1967
Reputation: 5063
If I remember correctly Spring Boot uses Jackson by default, and Jackson by default uses getters during serialization process, so you need to add getters for the fields you want to appear in JSON.
Alternatively, you can add this annotation to your class:
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
to use all fields, regardless of visibility, in your JSON
Upvotes: 5