The previous section wrote a helloWorld program return, now to write a json object data return.
Then we make some changes based on helloWorld:
1.User.java
package isenham;
@Component
public class User {
private String userId;
private String userName;
private String userAge;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserAge() {
return userAge;
}
public void setUserAge(String userAge) {
this.userAge = userAge;
}
}
2. HelloWorld.java modification
package isenham;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloWorld {
@Autowired
private User user;
@RequestMapping("/")
public String sayHelloWorld(){
return "hello world!";
}
@RequestMapping("/jsonUser")
public User jsonUser(){
user.setUserId("001");
user.setUserName("tom");
user.setUserAge("23");
return user;
}
}
3. Visit the browser http://127.0.0.1:8081/jsonUser/ to see {"userId":"001","userName":"tom","userAge":"23"}
( In fact, Spring Boot also refers to the JSON parsing package Jackson , so naturally we can use the annotation of the json property provided by Jackson on the User object )