
前后端JSON数据交互异常及解决方案
问题:后端接口使用@RequestBody接收前端JSON数据时,报错Cannot deserialize instance of java.lang.String out of START_ARRAY token。
问题根源
错误提示表明,后端期望接收一个数组(START_ARRAY token),但实际收到的是一个字符串(java.lang.String)。这通常是因为前端发送的JSON数据格式与后端期望的格式不一致。例如,后端定义了一个List<hkboattaskpath></hkboattaskpath>类型的属性,但前端却发送了一个该类型对象的JSON字符串表示,而不是一个JSON数组。
立即学习“Java免费学习笔记(深入)”;
解决方案
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
解决方法主要有两种:调整前端数据格式或修改后端代码进行数据处理。
List<hkboattaskpath></hkboattaskpath>,前端JSON数据应如下所示(示例):<code class="json">{
"isapp": "forandroid",
"taskname": "test",
"pathlist": [
{
"createtime": "2022-07-13 16:34:32",
"cycleindex": "1",
"id": "347",
"maxormin": [
{"latitude": 30, "longitude": 120},
{"latitude": 30, "longitude": 120}
],
"pathname": "test1",
"pathtype": "1",
"pointlist": [
{"latitude": 30, "longitude": 120},
{"latitude": 30, "longitude": 120}
]
},
{ /* ... other HkboatTaskPath objects ... */ }
]
}</code><code class="java">@PostMapping("/api/endpoint")
public ResponseEntity<Void> handleRequest(@RequestBody String jsonData) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
JsonNode rootNode = objectMapper.readTree(jsonData);
JsonNode pathList = rootNode.get("pathlist");
List<HkboatTaskPath> paths = objectMapper.readValue(pathList.toString(), new TypeReference<List<HkboatTaskPath>>() {});
// ... further processing of 'paths' ...
return ResponseEntity.ok().build();
}</code>预防措施
为了避免此类问题再次发生,建议:
通过以上方法,可以有效解决Cannot deserialize instance of java.lang.String out of START_ARRAY token错误,并预防此类问题的再次发生。
以上就是前后端JSON数据映射异常:如何解决`Cannot deserialize instance of java.lang.String out of START_ARRAY token`错误?的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号