上一篇
🔍 SpringBoot | 接口开发 | Controller返回JSON
注解驱动 �
@RestController
:自动将方法返回值转为JSON(等价于@Controller
+ @ResponseBody
)。 @ResponseBody
:单独标注方法时,强制返回JSON。 直接返回对象 🚀
@GetMapping("/user") public User getUser() { return new User("Alice", 25); // 自动序列化为JSON }
返回Map或集合 📦
@GetMapping("/list") public List<String> getList() { return Arrays.asList("A", "B", "C"); }
手动构建JSON 🛠️
ResponseEntity
自定义状态码和响应体: @GetMapping("/custom") public ResponseEntity<Map<String, Object>> customJson() { Map<String, Object> map = new HashMap<>(); map.put("code", 200); map.put("data", "Success"); return ResponseEntity.ok(map); }
序列化规则 ⚠️
@JsonIgnore
忽略敏感字段。 日期格式化 📅
application.properties
): spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.time-zone=GMT+8
@JsonFormat(pattern="yyyy-MM-dd")
。 统一响应体 ✨
Result<T>
),避免接口风格混乱。 public class Result<T> { private int code; private T data; // 构造方法 + Getter/Setter }
异常处理 ❗
@ExceptionHandler
捕获异常并返回JSON错误信息。 性能优化 🚄
server.compression.enabled=true
。 @JsonManagedReference
和@JsonBackReference
解决双向关联。 @JsonInclude(JsonInclude.Include.NON_NULL)
忽略空字段。 📌 :SpringBoot返回JSON只需专注业务逻辑,但需注意序列化规则、格式统一与性能!
本文由 续智阳 于2025-07-31发表在【云服务器提供商】,文中图片由(续智阳)上传,本平台仅提供信息存储服务;作者观点、意见不代表本站立场,如有侵权,请联系我们删除;若有图片侵权,请您准备原始证明材料和公证书后联系我方删除!
本文链接:https://vps.7tqx.com/wenda/499336.html
发表评论