java - springboot 返回响应实体返回 JSON
问题描述
我想在下面返回 JSON。
{“名称”:“杰基”}
邮递员给我错误。陈述
意外的“n”
这里是 Spring Boot 的新手。1 天大。有没有合适的方法来做到这一点?
// POST method here
@RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(@RequestBody Topic topic) {
if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
return Util.createResponseEntity("Name : jackie", HttpStatus.CREATED);
}
return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}
解决方案
创建模型并在该模型中存储值并从控制器返回模型。检查下面的代码。
class User{
private String name;
//getter and setter
}
@RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<User> addTopic(@RequestBody Topic topic) {
User user=new User();
user.setName("myname");
HttpHeaders httpHeaders = new HttpHeaders();
return new ResponseEntity<User>(user, httpHeaders, HttpStatus.CREATED);
}
推荐阅读
- sql-server - 遍历 SQL 表行并对 XML 节点求和
- python - 使用 Selenium [Python] 对元素的奇怪行为
- android - 音频播放和暂停 Ionic Creator 应用程序(音频流 - 广播应用程序)
- javascript - 如何使用 PHP 或 JS 复制 URL 仅在域的最后一部分,如帖子名称
- amp-html - 固定高度的 AMP 轮播不起作用
- c# - Amazon S3 MultiPartUpload C# 不工作
- java - 使用 Spring Web 客户端发送带有查询参数的 HTTP 通知
- windows - 窗口和 Z 位置
- c# - 在一定距离内让敌人跟随你
- sql - 在 SQL Server 中获取计数百分比