我在 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
类没有 setter/getter (至少从我在你的帖子中看到的)。添加 setter/getter ,这应该可以工作。
我认为你可以使用JpaRepository<T, ID>
而不是CrudRepository<T, ID>
所以在这种情况下不需要实例化另一个 List<Good>
,因为repository.findAll()
已返回List<Good>
里面JpaRepository
,尽管按照你的做法,它也应该可以正常工作。
Do I need to convert the Java Instances to JSON objects? If so, is there any framework to help us to do this job?
没有。 Spring 已经通过使用 Jackson 的序列化器为您完成了这项工作。
关于java - 如果我在 Spring Boot 中只返回 Java 实例数组,则 http 响应正文中有一个空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59681230/