我想在下面返回json。
{ “名字”:“杰基” }
邮递员给我错误。说明
意外的'n'
这里是春季靴子的新手。 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);
}
答案 0 :(得分:2)
在该模型中创建模型和存储值,并从控制器返回模型。 检查下面的代码。
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);
}
答案 1 :(得分:1)
尝试将回复包装在对象中。
class Response implements Serializable {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Controller可以是这样的:
@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);
}
答案 2 :(得分:1)
这是我使用的:
@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);
}
}