gpt4 book ai didi

java - Spring boot 应用程序无法在 PUT API 调用中映射 List 对象

转载 作者:行者123 更新时间:2023-12-02 09:11:51 24 4
gpt4 key购买 nike

我在 PUT/PATCH API 调用中使用对象列表,该调用对对象列表进行更新。下面是示例 POJO 和包装器对象。令我惊讶的是,请求映射失败。

POJO:

public class Product{


}


public class Products{

private List<Product> products;

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

public void setSubscription(List<Product> products) {
this.products= products;
}
}

Controller 类:

@Controller
@RequestMapping("app")
public class ProductController {

@Autowired
private ProductService productService ;





@RequestMapping(value = "/products", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
public @ResponseStatus(value = HttpStatus.NO_CONTENT) @ResponseBody void updateProducts(
@RequestBody Products products)
throws IllegalArgumentException, MalformedURLException {

productService .updateProducts(products);

}


@RequestMapping(value = "/products", method = RequestMethod.PATCH, produces = "application/json;charset=UTF-8")
public @ResponseStatus(value = HttpStatus.NO_CONTENT) @ResponseBody void updateProducts(
@RequestBody Products products)
throws IllegalArgumentException, MalformedURLException {

productService .updateProducts(products);

}

JSON 请求:

{

"name": "MySmartPhone",
"brand":"Samsung"

}

通过 postman h 进行本地测试的 URIttp://localhost:8080/app/products

最佳答案

您的 Controller 有Products,它是Product列表。您需要在 JSON 中传递相同的模式。

假设您的产品有以下字段

public class Product{
public String name;
public String brand;
}

您的请求 JSON 应该是这样的

{
"products" : [
{
"name": "MySmartPhone",
"brand":"Samsung"
}
]
}

编辑1:

我在 POSTMAN 中尝试了你的代码,我能够看到映射。检查在正文中的 Postman 中您是否选择了 application/json

@RequestMapping(value = "/products", method = RequestMethod.PUT, produces = "application/json;charset=UTF-8")
public @ResponseStatus(value = HttpStatus.NO_CONTENT) @ResponseBody void updateProducts(
@RequestBody Products products) {
System.out.println(products.getProducts().get(0).getName());
}

OUTPUT:
MySmartPhone

关于java - Spring boot 应用程序无法在 PUT API 调用中映射 List 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59350837/

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