首页 > 解决方案 > 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);
    }

标签: javajsonspring-boot

解决方案


创建模型并在该模型中存储值并从控制器返回模型。检查下面的代码。

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);   
    }

推荐阅读