gpt4 book ai didi

java - 如何在 Spring Controller 中读取 JSON 数组值

转载 作者:行者123 更新时间:2023-12-01 17:47:37 24 4
gpt4 key购买 nike

我想迭代产品并获取名称、代码和价格列表并在我的模型类中设置。任何帮助将非常感激 - 我该如何迭代这个。当我使用 obj.get("Products") 时 - 它只是打印为字符串 - 被困在迭代中。

{
"id": "skd3303ll333",
"Products": [{
"name": "apple",
"code": "iphone-393",
"price": "1939"

},
{
"name": "ipad",
"code": "ipad-3939",
"price": "900"

}
]
}


@PostMapping(path="/create", consumes=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> create(@RequestBody Map<String, Object> obj ) {
System.out.println("Products :" + obj.get("Products"));
}

最佳答案

有两种方法可以做到这一点,

1)通过类型转换(我个人不喜欢这个)

List<Map<Object,Object>> productslist = (List<Map<Object, Object>>) obj.get("products");
for(Map entry: productslist) {
for(Object s: entry.keySet()) {
System.out.println(s.toString());
System.out.println(entry.get(s).toString());

}
}

2) 直接映射到模型类,对于这种方法,您需要在构建路径中使用 Jackson 库

@JsonIgnoreProperties(unknown =true)
public class Customer {

@JsonProperty("id")
private String id;
@JsonProperty("products")
private List<Products> products;

public String getId() {
return id;
}

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

public List<Products> getProducts() {
return products;
}

public void setProducts(List<Products> products) {
this.products = products;
}

}
@JsonIgnoreProperties(unknown =true)
class Products{
@JsonProperty("name")
private String name;
@JsonProperty("code")
private String code;
@JsonProperty("price")
private String price;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

}

Controller

public ResponseEntity<Object> create(@RequestBody  Customer obj ) {

关于java - 如何在 Spring Controller 中读取 JSON 数组值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53327517/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com