Bird
0
0

You want to create a REST controller that returns a list of user names as JSON. Which code snippet correctly achieves this?

hard📝 component behavior Q8 of 15
Spring Boot - REST Controllers
You want to create a REST controller that returns a list of user names as JSON. Which code snippet correctly achieves this?
A@RestController public class UserController { @GetMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Carol"); } }
B@RestController public class UserController { @GetMapping("/users") public String getUsers() { return "Alice, Bob, Carol"; } }
C@Controller public class UserController { @GetMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Carol"); } }
D@RestController public class UserController { @PostMapping("/users") public List<String> getUsers() { return List.of("Alice", "Bob", "Carol"); } }
Step-by-Step Solution
Solution:
  1. Step 1: Check annotations and return type

    @RestController with @GetMapping is correct for returning data on GET requests. Returning List will auto-convert to JSON array.
  2. Step 2: Eliminate incorrect options

    @RestController public class UserController { @GetMapping("/users") public String getUsers() { return "Alice, Bob, Carol"; } } returns a plain string, not JSON array. @Controller public class UserController { @GetMapping("/users") public List getUsers() { return List.of("Alice", "Bob", "Carol"); } } uses @Controller which does not auto-convert. @RestController public class UserController { @PostMapping("/users") public List getUsers() { return List.of("Alice", "Bob", "Carol"); } } uses @PostMapping which is wrong for GET requests.
  3. Final Answer:

    Option A code snippet correctly returns JSON list of user names -> Option A
  4. Quick Check:

    @RestController + @GetMapping + List return = JSON array [OK]
Quick Trick: Use @RestController + @GetMapping + List return for JSON arrays [OK]
Common Mistakes:
  • Using @Controller instead of @RestController
  • Returning plain strings instead of objects or lists
  • Using wrong HTTP method annotation

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Spring Boot Quizzes