SpringBoot返回json数据
程序员文章站
2022-03-10 12:09:12
...
1.pom文件
<parent>
<!-- pring-boot-start-parent,可以提供dependency management,依赖管理,
引入以后在其它dependency的时候就不需要version了 -->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.3.3.RELEASE</version>
</parent>
<dependencies>
<!-- spring-boot-start-web包含了spring webmvc和tomcat等web开发的特性 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
2.测试的DTO实体类
package com.aruisi.dto;
public class DemoDto {
private String userId;
private String usernName;
private String phoneNumber;
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUsernName() {
return usernName;
}
public void setUsernName(String usernName) {
this.usernName = usernName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
3.测试的controller类
package com.aruisi.controller;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.aruisi.dto.DemoDto;
/**
* @SpringBootApplication申明让spring boot自动给程序进行必要的配置,
* 等价于以默认属性使用@Configuration,@EnableAutoConfiguration和@ComponentScan
* @RestController返回json字符串的数据
* @author zmk
*/
@RestController
@SpringBootApplication
public class DemoController {
@RequestMapping("/demo")
public DemoDto demo(){
DemoDto demoDto = new DemoDto();
demoDto.setPhoneNumber("xxxxxxxxxxx");
demoDto.setUserId("123456789");
demoDto.setUsernName("zmk");
return demoDto;
}
public static void main(String[] args) {
SpringApplication.run(DemoController.class, args);
}
}
4.右键project – Run as –Maven build – 在Goals里输入spring-boot:run,然后Apply,最后点击Run。在浏览器访问地址:http://127.0.0.1:8080/demo返回如下数据:
{
"userId": "123456789",
"usernName": "zmk",
"phoneNumber": "xxxxxxxxxxx"
}
上一篇: JSON简介
下一篇: Golang中JSON文件处理
推荐阅读