首页 > 解决方案 > 如果我只在 Spring Boot 中返回 Java 实例数组,则 http 响应正文中有一个空数组

问题描述

我在 Spring-Boot-Get-Started 项目中返回了一组 Java 实例。

package com.wepay.business.resource;

import com.wepay.business.model.Good;
import com.wepay.business.repo.GoodRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

@CrossOrigin(origins = {"http://localhost:3000", "http://localhost:9000", "http://localhost:8083"})
@RestController
@RequestMapping("/api")
public class GoodResource {
    @Autowired
    GoodRepository repository;

    @GetMapping("/getGood")
    public List<Good> getAllGoods() {
        List<Good> goods = new ArrayList<>();
        repository.findAll().forEach(goods::add);
        return goods;
    }
}
package com.wepay.business.repo;

import com.wepay.business.model.Good;
import org.springframework.data.repository.CrudRepository;

public interface GoodRepository extends CrudRepository<Good, Long> {

}
package com.wepay.business.model;

import javax.persistence.*;


@Entity
@Table(name = "good")
public class Good {

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private long id;

  @Column(name = "name")
  private String name;

  @Column(name = "price")
  private double price;

  @Column(name = "img")
  private String img;

  @Column(name = "info")
  private String info;

  @Column(name = "amount")
  private int amount;

  @Column(name = "address")
  private  String address;

  @Column(name = "soldAmount")
  private String soldAmount;

  @Column(name = "sellerId")
  private String sellerId;

  public Good(){

  }

  public Good(String name, Double price, String info, int amount) {
    this.name = name;
    this.price = price;
    this.info = info;
    this.amount = amount;
  }

  public Good(Long id, String goodName, Double unitPrice, String goodInfo, int amount) {
      this(goodName, unitPrice, goodInfo, amount);
      this.id = id;
  }

  public void setId(Long id) {
    this.id = id;
  }
}

的值goods是 Java Instacnes 的数组, 在此处输入图像描述 但是 http 响应体中只有一个空数组。

在此处输入图像描述

我想我应该返回一个 JSON 对象数组而不是 Java 实例。

我需要将 Java 实例转换为 JSON 对象吗?如果是这样,是否有任何框架可以帮助我们完成这项工作?

自上周以来,我一直被这个问题阻止。提前致谢。

标签: javajsonspringspring-boot

解决方案


问题在于您的Good班级没有吸气剂(至少我在您的帖子中看到的)。添加吸气剂,这应该可以工作。

我认为你可以使用JpaRepository<T, ID>而不是CrudRepository<T, ID>so 在这种情况下不需要实例化另一个List<Good>,因为repository.findAll()已经List<Good>在 内部返回JpaRepository,尽管按照你的方式,它也应该正常工作。

我需要将 Java 实例转换为 JSON 对象吗?如果是这样,是否有任何框架可以帮助我们完成这项工作?

不,Spring 已经通过使用 Jackson 的序列化程序为您做到了。


推荐阅读