java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > SpringBoot JSON解析错误

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

作者:码农阿豪@新空间

在开发Spring Boot RESTful API时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON解析错误(如400 Bad Request)是常见的开发问题之一,本文将通过一个实际案例,详细分析如何排查和解决JSON解析错误,并总结最佳实践,需要的朋友可以参考下

问题背景

1. 问题描述

开发者在调用本地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"
}

2. 错误分析

错误信息表明:

解决方案

1. 手动重新输入JSON

问题原因:JSON可能是从网页、Word文档或富文本编辑器复制的,导致包含隐藏字符。
解决方法:手动重新输入JSON,避免复制粘贴:

{
  "channelId": 100000132,
  "platformAccount": "yien",
  "platformPwd": "123456",
  "enName": "jinYiMu",
  "grabDays": 15,
  "aesPwd": "example"
}

2. 使用工具清理JSON

推荐工具:

示例:

// 格式化前(可能含隐藏字符)
{ "channelId": 100000132 }

// 格式化后(标准JSON)
{
  "channelId": 100000132
}

3. 检查请求原始数据

使用 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编码,说明存在非法字符。

4. 代码层面过滤非法字符

如果问题持续,可以在Java后端对输入进行清理:

import org.springframework.util.StringUtils;

public class SpiderParam {
    private String enName;

    // 移除所有空白字符
    public void setEnName(String enName) {
        this.enName = enName.replaceAll("\\u00A0", ""); // 移除  
    }
}

深入排查:Spring Boot的JSON解析机制

1. Jackson库的工作流程

Spring Boot默认使用 Jackson 解析JSON,流程如下:

2. 关键日志配置

在 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))

3. 使用 @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

最佳实践

1. 如何避免JSON解析错误?

问题解决方案
非法空白字符手动输入JSON,或用工具清理
字段名不匹配使用 @JsonProperty("en_name")
缺少必填字段添加 @NotNull 注解
类型不匹配确保JSON和Java类型一致

2. 推荐工具

工具用途
Postman测试API,生成标准JSON
VS Code格式化JSON,显示隐藏字符
curl快速测试请求

总结

本文通过一个实际案例,详细分析了Spring Boot中JSON解析错误的排查方法:

关键点:

到此这篇关于SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法的文章就介绍到这了,更多相关SpringBoot JSON解析错误内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文