spring-boot之json对象数据返回

上一节写了一个helloWorld的程序返回,现在来写一个json对象数据的返回。

那我们在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修改

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.访问浏览器http://127.0.0.1:8081/jsonUser/可看到{"userId":"001","userName":"tom","userAge":"23"}

其实Spring Boot也是引用了JSON解析包Jackson,那么自然我们就可以在User对象上使用Jackson提供的json属性的注解

猜你喜欢

转载自lsj626472785.iteye.com/blog/2343748
今日推荐