How to create a @Restcontroller that returns JSON from an array of users

Jonathan Reeves :

I am have been trying to solve this challenge for a while now. I am a JavaScript developer but have been trying out Spring Boot and Java and am running into an issue. In the below code I need to figure out how to write the @RestController logic to return JSON from the list of users created below in the User class. I am not sure how to go about doing that since this is all new to me.

package usersExample;

import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicLong;

@RestController
public class UsersController {
    /* Please insert your code here to make the tests pass */
}

@Service
class UserService {
    public List<User> all() {
        List<User> users = new ArrayList<User>();
        users.add(new User("Bob"));
        users.add(new User("Christina"));
        users.add(new User("Steve"));
        return users;
    }
}

class User {
  private final String name;
  public User(String name) {
      this.name = name;
  }
  public String getName() {
      return name;
  }
}
Sebastian I. :

Since you're using @RestController, the return value is already a JSON (spring-boot does the conversion without adding additional dependencies because it already include the Jackson library). You can simply create a method in your controller which will return a List of users. One comment about your code: use proper method names like findAll() instead of all().

@GetMapping("/find-all")
public List<User> findAll()
{
      return userService.findAll();
}

P.S.: And in case that the code you've added is the same with the one you're running, I suggest you to create separate classes for User and UserService.

EDIT: The conversion of a simple object into a JSON object is done using getters. How is it working? Let's take your example:

class User {
  private final String name;
  public String getName() {
      return name;
  }
}

The converter will look for methods starting with the get keyword and set everything after that as an attribute name with first letter converted to lower case, this means that the ONLY attribute (because you have only 1 getter) will look like this: name : -value here-.

Now you may be asking some questions like :

1)

Q: What happens if you change your getName() method to getname() ?

A: Will work the same

2)

Q: What happens if you don't provide a getter to a field?

A: The field won't be converted to a JSON property

3)

Q: What happens if you change getName() method to getMyName() ?

A: The attribute name will be myName: -value-

So, if these have been said, if you want to change your JSON structure, there are many solutions:

1) Change the getter names (not really recommended)

2) Use the @JsonProperty annotation. E.g.:

private String name;

@JsonProperty("name")
public String thismethodwontworkwithoutjsonproperty() {
    return this.name;
}

3) Create a DTO object UserDTO and return this instead of User. And in your controller you can convert the user to an userDTO object.

public class UserDTO {
   private String fullName; 
   //getter; setter;
}

and

public class User {
  private String firstName;
  private String lastName;
  //getter;setter;
}

And eventually, you make the conversion like this:

@GetMapping("/getUser")
public User returnUser() {
    User user = new User();
    user.setFirstName("Stack");
    user.setLastName("Overflow");
    UserDto userDto = convertUser(user);
    return userDto;
}

private UserDTO convertUser(User user) {
    UserDTO userDTO = new UserDTO();
    userDTO.setFullName(user.getFirstName() + " " + user.getLastName());
    return userDTO;
}

But I would suggest you to structure your application and add a facade layer which will make this conversion instead of creating convertUser() method in the controller.

Output:

{
  "fullName":"Stack Overflow";
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=12497&siteId=1