You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring+Postgres服务:jQuery调用REST接口存数据遇JsonParseException异常

解决方案:修复Spring + jQuery POST请求的JSON解析异常

这个问题我之前也碰到过,核心原因是请求格式不匹配:jQuery默认会把data参数转成application/x-www-form-urlencoded格式(就是表单提交的那种键值对格式),但你的Spring RestController如果用@RequestBody接收对象,它期望的是application/json格式的请求体,所以才会抛出JsonParseException。

下面分前端jQuery和后端Spring Controller两部分给出修改步骤:


一、前端jQuery代码修改

需要做两个关键调整:

  1. 指定contentType: "application/json",明确告诉服务器我们发送的是JSON格式数据
  2. 用JSON.stringify()把JavaScript对象转成JSON字符串,避免jQuery自动转成表单格式

修改后的完整代码:

$.ajax({
    url: 'http://localhost:8080/products',
    type: "POST",
    // 把对象转成标准JSON字符串
    data: JSON.stringify({ 
        "productName":"product", 
        "amount": 123, 
        "dateArrival": 1522345884907
    }),
    // 关键:指定请求体的MIME类型为JSON
    contentType: "application/json",
    dataType: "json",
    success: function (res) {
        console.log("产品保存成功!", res);
        // 这里写你的成功逻辑
    },
    error: function(xhr, status, error) {
        console.error("请求失败:", error);
        // 这里写错误处理逻辑
    }
});

二、后端Spring Controller调整

确保你的Controller满足以下要求:

1. 用@RequestBody接收实体对象

你的方法参数必须加上@RequestBody注解,这样Spring才会把请求体的JSON字符串解析成对应的实体类对象:

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/products")
public class ProductController {

    private final ProductRepository productRepository;

    // 构造注入(Spring 4.3+推荐的方式,无需@Autowired)
    public ProductController(ProductRepository productRepository) {
        this.productRepository = productRepository;
    }

    @PostMapping
    public ResponseEntity<Product> createProduct(@RequestBody Product product) {
        Product savedProduct = productRepository.save(product);
        // 返回201 Created状态码和保存后的对象
        return ResponseEntity.status(HttpStatus.CREATED).body(savedProduct);
    }
}

2. 确保实体类字段与JSON键匹配

你的Product实体类的字段名要和JSON里的键名一致(Spring默认支持驼峰命名匹配,比如JSON里的productName对应实体的private String productName;)。另外,如果dateArrival是Date或Java 8+的LocalDateTime类型,Spring会自动把时间戳转成对应的日期对象(如果用LocalDateTime,需要确保项目引入jackson-datatype-jsr310依赖,Maven配置如下:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

3. 处理跨域问题(如果需要)

如果你的前端页面运行端口和后端8080不一致,会出现跨域问题,这时候可以给Controller加@CrossOrigin注解,或者配置全局跨域:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebCorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*") // 生产环境请替换成具体前端域名,比如"http://localhost:3000"
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*");
    }
}

关键总结

  • 前端必须设置contentType为application/json,并且把数据转成JSON字符串
  • 后端必须用**@RequestBody**注解接收实体对象
  • 实体类字段要和JSON键名保持一致(注意大小写匹配)
  • 别忘了处理可能的跨域问题

内容的提问来源于stack exchange,提问作者ydd

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:01:53