分分钟搞定!Spring Boot返回JSON数据

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37774696/article/details/85002180

在web开发中,返回json数据是最常见的交互形式。有很多第三方的jar包供我们使用,不过在springboot中更加简单!接下来让我们一起看看怎么使用springboot返回json:

1.创建springboot的项目

这里建议大家可以到 https://start.spring.io/ 中创建一个maven模板的是springboot 的demo项目
在这里插入图片描述

2.加入依赖

<parent>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-parent</artifactId>
	<version>2.0.2.RELEASE</version>
	<relativePath /> <!-- lookup parent from repository -->
</parent> 
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

除了引入是springboot自带的parent依赖外,我们只需要添加springboot-starter-web 依赖包即可。

3.返回json数据格式的定义

3.1定义返回的格式:

可以在controller类前加入@RestController注解或者在方法前面加上@ResponseBody定义。例如:

@RestController
@RequestMapping("/api")
public class AccountController {
	@Autowired
	private IUserService userService;
	@PostMapping("/service/register")
	public Result register(@RequestBody User u) {
		User user = userService.findByName(u.getUsername());
		if (user != null) {
			return ResultUtil.error(1, "账号名字已存在");
		} else {
			if (userService.findByEmail(u.getEmail()) != null) {
				return ResultUtil.error(1, "该邮箱已注册");
			}
			u.setPassword(DESUtils.encryptBasedDes(u.getPassword()));
			userService.saveUser(u);
			return ResultUtil.success(null);
		}
	}

3.2自定义输出格式:

可以在对象的定义中加入
@JsonProperty:可以自定义属性标签名字;
@JsonIngore:可以来忽略不想输出的某个属性的标签;
@JsonInclude:可以用来动态包含属性的标签,如可以不含为null值的属性
这些注解去自定义我们返回数据的格式。

猜你喜欢

转载自blog.csdn.net/m0_37774696/article/details/85002180
今日推荐