[英]how to retrieve a value from json in spring boot in post request
Hi I am trying to follow this article to consume a json file to retrieve a value from it and do some processing on it: https://www.baeldung.com/spring-boot-json您好我正在尝试按照这篇文章使用 json 文件以从中检索值并对其进行一些处理: https://www.baeldung.com/spring-boot-json
I am following this github repo and students folder: https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/students我正在关注这个 github 回购和学生文件夹: https://github.com/eugenp/tutorials/tree/master/spring-boot-modules/spring-boot-mvc-2/src/main/java/com/baeldung/学生们
the thing is in post mapping in StudentController.java
, I saw this:事情在
StudentController.java
的后期映射中,我看到了这个:
@PostMapping("/")
public ResponseEntity<Student> create(@RequestBody Student student) throws URISyntaxException {
Student createdStudent = service.create(student);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(createdStudent.getId())
.toUri();
return ResponseEntity.created(uri)
.body(createdStudent);
}
He's passing student object in @RequestBody
, what if I need to extract a value from a json, like this post request is receiving for example json like this:他在
@RequestBody
中传递学生 object,如果我需要从 json 中提取一个值怎么办,就像这个帖子请求正在接收例如 json 是这样的:
{'key':'val1',
'key2':'val2'
}
and in my spring boot app I need to retrieve this json object and get to do some processing on 'val1', which should be retrieved something like this object['key'], I am not sure how to do so?在我的 spring 启动应用程序中,我需要检索此 json object 并开始对“val1”进行一些处理,应该检索类似于此对象['key']的内容,我不确定该怎么做? can u please help me in this?
你能帮我吗?
I did not completely get what you are trying to do but if i'm correct, you are trying to retrieve a request body manually and do some business on it.我没有完全明白你想要做什么,但如果我是正确的,你正在尝试手动检索请求正文并在其上做一些业务。 To do that:
要做到这一点:
public ResponseEntity<?> login(HttpServletRequest request) {
String body = request.getReader().lines().collect(Collectors.joining(System.lineSeperator()));
ObjectMapper mapper = new JsonMapper();
JsonNode json = mapper.readTree(body);
String email = json.get("email").asText();
String password = json.get("password").asText();
...
}
this is a code sample from another project, i hope it helps.这是另一个项目的代码示例,希望对您有所帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.