gpt4 book ai didi

java - 嵌套 json 到 java 对象 List 返回预期值,但 List 返回 null 值
转载 作者:行者123 更新时间:2023-12-02 09:58:33 24 4
gpt4 key购买 nike

我有以下 json,我想将其存储到 java 对象中:

{  
"shippingDetails":{
"address":"khalda",
"country":"Jordan",
"town":"amman"
},
"product":[
{
"product":{
"id":2,
"name":"Wrap Dress",
"price":330,
"salePrice":165,
"discount":50,
"pictures":[
"assets/images/fashion/product/1.jpg",
"assets/images/fashion/product/1.jpg",
"assets/images/fashion/product/1.jpg",
"assets/images/fashion/product/1.jpg"
],
"shortDetails":"test",
"description":"test",
"stock":2,
"new":true,
"sale":false,
"category":"women",
"colors":[
"gray",
"orange"
],
"size":[
"M",
"L",
"XL"
],
"tags":[
"caprese",
"puma",
"lifestyle"
],
"variants":[
{
"color":"gray",
"images":"assets/images/fashion/product/1.jpg"
},
{
"color":"orange",
"images":"assets/images/fashion/product/1.jpg"
}
]
},
"quantity":1
}
],
"totalAmount":330
}

我有以下 java beans:主要对象类称为 Order,它有

@Data
@Entity
@Table(name = "orders")
public class Order {
@Id
@Column(name="shippingDetailsId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@OneToOne(cascade = {CascadeType.ALL})
private ShippingDetails shippingDetails;
//@OneToMany(cascade = {CascadeType.ALL})
//List<Product> products;
List<Object> product = new ArrayList<>();
private float totalAmount;
}

内部对象类是:

@Data
@Entity
@Table(name = "products")
public class Product {
@Id
@Column(name = "productId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne
private Order order;
private Boolean isNew;
private String salePrice;
private String shortDetails;
private String discount;
private String description;
private Variants[] variants;
private String[] pictures;
private String[] colors;
private String[] tags;
private String sale;
private String[] size;
private String price;
private String name;
private String stock;
private String category;
}

以及运输详细信息 bean:

@Data
@Entity
@Table(name = "shippingDetails")
public class ShippingDetails {
@Id
@Column(name="shippingDetailsId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String address;
private String country;
private String town;
}

我尝试了很多方法,但没有一个有效,首先我尝试在 Controller 中接受一个 Order 对象并尝试存储它,但没有成功,结果是:

使用“列表”时,所有值都会根据需要打印到控制台并插入到数据库中,但在同一个表“订单”中,这不是我要找的,我希望将产品保存在名为“产品”的单独表中所以我使用了List。

当使用List时,产品的值为null。

然后我尝试从我的 Controller 接受一个字符串并使用 GSON 库将其转换为 Order 对象,但它不起作用,我遇到了多种异常试图弄清楚并尝试了多种方法在 stackoverflow 和其他网站上提到过,但没有运气,请注意我已经验证了我的 json 字符串并且它是一个有效的 json。

最佳答案

如果您看到 JSON 中的层次结构,它与您的 Java 对象不匹配。

 "product":[  // Parent-Product
{
"product":{ // Child-Product
"id":2,

直接映射到 Java 会是这样的

List<Map<String,Product>> products

如果您可以选择更改 JSON 文件,请更改为如下所示的内容并删除父子产品层次结构。

"product":[
{
"id":..
},
{
"id":..
}
..
]

关于java - 嵌套 json 到 java 对象 List<Object> 返回预期值,但 List<DefinedObject> 返回 null 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55798617/

24 4 0