在开发Spring Boot RESTful API时,客户端与服务端的数据交互通常使用JSON格式。然而,JSON解析错误(如400 Bad Request)是常见的开发问题之一。本文将通过一个实际案例,详细分析如何排查和解决JSON解析错误,并总结最佳实践。
开发者在调用本地Spring Boot接口时,遇到400 Bad Request错误:
curl --location 'http://localhost:8089/after/spider' \
--header 'Content-Type: application/json' \
--data '{
"channelId": 100000132,
"platformAccount": "yien",
"platformPwd": "123456",
"enName": "jinYiMu",
"grabDays": 15,
"aesPwd": "example"
}'返回错误:
{
"timestamp": "2025-06-12T03:04:50.459+00:00",
"status": 400,
"error": "Bad Request",
"message": "JSON parse error: Unexpected character (' ' (code 160)): was expecting double-quote to start field name",
"path": "/after/spider"
}错误信息表明:
' ' (code 160)(即HTML的空格 )。问题原因:JSON可能是从网页、Word文档或富文本编辑器复制的,导致包含隐藏字符。 解决方法:手动重新输入JSON,避免复制粘贴:
{
"channelId": 100000132,
"platformAccount": "yien",
"platformPwd": "123456",
"enName": "jinYiMu",
"grabDays": 15,
"aesPwd": "example"
}推荐工具:
示例:
// 格式化前(可能含隐藏字符)
{ "channelId": 100000132 }
// 格式化后(标准JSON)
{
"channelId": 100000132
}使用 hexdump 或 xxd 查看请求体中的隐藏字符:
echo '{
"channelId": 100000132
}' | hexdump -C输出示例:
00000000 7b 0a c2 a0 22 63 68 61 6e 6e 65 6c 49 64 22 3a |{..."channelId":|其中 c2 a0 是 的UTF-8编码,说明存在非法字符。
如果问题持续,可以在Java后端对输入进行清理:
import org.springframework.util.StringUtils;
public class SpiderParam {
private String enName;
// 移除所有空白字符
public void setEnName(String enName) {
this.enName = enName.replaceAll("\\u00A0", ""); // 移除
}
}Spring Boot默认使用 Jackson 解析JSON,流程如下:
DispatcherServlet 接收请求,交给 HttpMessageConverter 处理。MappingJackson2HttpMessageConverter 使用 ObjectMapper 解析JSON。JsonParseException,返回400错误。在 application.yml 中启用详细日志:
logging:
level:
org.springframework.web: DEBUG
org.springframework.validation: DEBUG
server:
error:
include-binding-errors: always
include-message: always日志会显示具体的解析错误,例如:
JSON parse error: Unexpected character (' ' (code 160))@Valid 进行参数校验在Controller中添加 @Valid 注解,捕获校验错误:
@PostMapping("/spider")
public ResponseEntity<String> spider(@Valid @RequestBody SpiderParam spiderParam) {
return ResponseEntity.ok("Success");
}全局异常处理:
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ResponseEntity<String> handleValidationException(MethodArgumentNotValidException ex) {
String errorMsg = ex.getBindingResult().getFieldErrors().stream()
.map(error -> error.getField() + ": " + error.getDefaultMessage())
.collect(Collectors.joining(", "));
return ResponseEntity.badRequest().body(errorMsg);
}
}错误示例:
channelId: must not be null, platformAccount: must not be blank问题 | 解决方案 |
|---|---|
非法空白字符 | 手动输入JSON,或用工具清理 |
字段名不匹配 | 使用 @JsonProperty("en_name") |
缺少必填字段 | 添加 @NotNull 注解 |
类型不匹配 | 确保JSON和Java类型一致 |
工具 | 用途 |
|---|---|
Postman | 测试API,生成标准JSON |
VS Code | 格式化JSON,显示隐藏字符 |
curl | 快速测试请求 |
本文通过一个实际案例,详细分析了Spring Boot中JSON解析错误的排查方法:
关键点:
@Valid 进行校验,提高代码健壮性。希望本文能帮助你高效解决JSON解析问题! 🚀