2

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?

1
  • How does the User look like? Commented Jul 11, 2018 at 9:03

1 Answer 1

5

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.