java - 如果我只在 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 对象吗?如果是这样,是否有任何框架可以帮助我们完成这项工作?
自上周以来,我一直被这个问题阻止。提前致谢。
解决方案
问题在于您的Good
班级没有吸气剂(至少我在您的帖子中看到的)。添加吸气剂,这应该可以工作。
我认为你可以使用JpaRepository<T, ID>
而不是CrudRepository<T, ID>
so 在这种情况下不需要实例化另一个List<Good>
,因为repository.findAll()
已经List<Good>
在 内部返回JpaRepository
,尽管按照你的方式,它也应该正常工作。
我需要将 Java 实例转换为 JSON 对象吗?如果是这样,是否有任何框架可以帮助我们完成这项工作?
不,Spring 已经通过使用 Jackson 的序列化程序为您做到了。
推荐阅读
- java - 在android应用程序中集成gmail登录的问题?
- python - 如何创建一个从元组列表中获取随机元组并在 python 中生成基本图的程序?
- linux - 在新版本中使用 docker rootless
- php - Codeigniter - 如何获取为其提供重复值的列名
- angular - 错误的重定向到本地主机
- haskell - Haskell 从 bmp Image 获取矩阵
- api - Netscalar 重定向请求到 OpenShift 路由
- laravel - 如何从控制器显示数据到刀片视图以及如何从远程 api 进行路由?拉拉维尔
- php - 如何在代码点火器中输出外键数据
- python - 如何使用烧瓶在应用程序中返回 API 对象