springboot返回响应实体返回JSON

krugob8w  于 2023-01-06  发布在  Spring
关注(0)|答案(4)|浏览(259)

我想在下面返回JSON。
{“姓名”:“杰基”}
Postman 给我报错了。
意外的“n”
新到春 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);
    }
tzdcorbm

tzdcorbm1#

创建模型并在模型中存储值,然后从控制器返回模型.检查下面的代码.

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

gcxthw6b2#

试着用object来 Package 你的回答。

class Response implements Serializable {
    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

控制器可以是这样的:

@RequestMapping(method = RequestMethod.POST , produces = "application/json")
ResponseEntity<?> addTopic(@RequestBody Topic topic) {

    if (Util.save(topicRepository, new Topic(topic.getTopicName(), topic.getQuestionCount())) != null) {
        Response response = new Response();
        response.setName("jackie");
        return new ResponseEntity<>(response, HttpStatus.CREATED);
    }
    return Util.createResponseEntity("Error creating resource", HttpStatus.BAD_REQUEST);
}
dffbzjpn

dffbzjpn3#

@PostMapping("/register/service/provider")
public ResponseEntity<?> registerServiceProvider(@RequestBody ServiceProviderRequestPayload providerContext) {

    try {
        if (providerContext == null)
            throw new BadRequestException("the request body can not be null or empty.");

        if (!providerContext.isValid())
            throw new BadRequestException("The request body doesn't seems to be valid");

        return ResponseEntity.ok().contentType(MediaType.APPLICATION_JSON).body(new ObjectMapper().writeValueAsString(providerContext));
    } catch (BadRequestException | IllegalArgumentException e) {
        return ResponseEntity.badRequest().header("message", e.getMessage())
                .contentType(MediaType.APPLICATION_JSON).build();
    } catch (DuplicateKeyException keyException) {
        return ResponseEntity.badRequest().header("message", "There seems to be farmer config" + keyException.getCause())
                .contentType(MediaType.APPLICATION_JSON).build();
    } catch (JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}
iovurdzv

iovurdzv4#

这是我使用的:

@GetMapping(produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Map<String, String>> hello() {
    try {
        Map<String, String> body = new HashMap<>();
        body.put("message", "Hello world");
        return new ResponseEntity<>(body, HttpStatus.OK);
    } catch (Exception e) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

相关问题