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

在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值的属性
这些注解去自定义我们返回数据的格式。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值