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

Java API Get方法无法返回JSON数据仅显示空大括号求助

问题排查与解决建议

1. 检查Product类的序列化配置

这是最可能的原因,Jackson序列化实体类需要满足以下条件:

  • 必须存在无参构造函数(如果定义了带参构造,需显式声明无参构造)
  • 实体类字段需要对应getter方法(Jackson默认通过getter获取字段值)
  • 私有字段若未提供getter,可通过@JsonProperty注解标记为可序列化

示例修正后的Product类:

public class Product {
    private Integer id;
    private String name;
    private Double price;

    // 必须添加无参构造
    public Product() {}

    // 业务所需的带参构造
    public Product(Integer id, String name, Double price) {
        this.id = id;
        this.name = name;
        this.price = price;
    }

    // 所有字段的getter方法
    public Integer getId() { return id; }
    public String getName() { return name; }
    public Double getPrice() { return price; }

    // setter方法按需添加
    public void setId(Integer id) { this.id = id; }
    public void setName(String name) { this.name = name; }
    public void setPrice(Double price) { this.price = price; }
}

2. 确认Jackson依赖正常引入

如果是Spring Boot项目,确保spring-boot-starter-web依赖已添加(该依赖默认包含Jackson序列化组件):

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

非Spring Boot项目需手动添加Jackson核心依赖:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.15.2</version> <!-- 使用最新稳定版本 -->
</dependency>

3. 排查循环引用问题

若Product类关联了其他实体(如Category)且存在双向引用,会导致Jackson序列化时陷入循环,最终返回空JSON。解决方式:

  • 在反向引用字段上添加@JsonIgnore注解,忽略该字段的序列化
  • 使用@JsonManagedReference和@JsonBackReference标记双向关联关系

示例:

public class Product {
    // ...其他字段

    @JsonIgnore // 忽略该字段的序列化,避免循环引用
    private Category category;
}

4. 显式指定响应Content-Type

在Controller的@GetMapping注解中添加produces属性,明确返回JSON类型:

@GetMapping(value = "/products", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<List<Product>> getProducts() {
    return getProductService.execute(null);
}

5. 调试序列化过程

在Service中手动执行序列化操作,查看是否抛出异常,精准定位问题:

@Override
public ResponseEntity<List<Product>> execute(Void input) {
    List<Product> products = productRepository.findAll();
    // 手动序列化调试
    try {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(products);
        System.out.println("序列化结果: " + json); // 查看序列化后的JSON内容
    } catch (JsonProcessingException e) {
        e.printStackTrace(); // 捕获并打印序列化异常
    }
    return ResponseEntity.status(HttpStatus.OK).body(products);
}

内容的提问来源于stack exchange,提问作者Đạt Phạm

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.15 08:27:18