gpt4 book ai didi

json - json 响应 spring boot 中缺少字段

转载 作者:行者123 更新时间:2023-12-05 06:11:24 25 4
gpt4 key购买 nike

我的 Stock 响应类只有两个字段,如下所示

class StockResponse {

private String orderId;
private String status;

//constructor

//getters and setters

}

还有 Controller 如下

@RestController
@RequestMapping("/stocks")
public class StockController {

private static List<StockResponse> stocktList = new ArrayList <StockResponse > ();

static {
stocktList.add(new StockResponse("order1", "AVAILABLE"));
stocktList.add(new StockResponse("order2", "AVAILABLE"));
stocktList.add(new StockResponse("order3", "NOT AVAILABLE"));
stocktList.add(new StockResponse("order4", "AVAILABLE"));

}

@GetMapping("/")
public ResponseEntity < ? > getProsucts() {

return ResponseEntity.ok(stocktList);

}

@GetMapping(path="/{id}", produces = "application/json;charset=UTF-8")
public StockResponse getProsucts(@PathVariable String id) {

StockResponse product = findOrder(id);

if (product == null) {
// return ResponseEntity.badRequest(product)
// .body("Invalid product Id");
}
System.out.println(product.getOrderId());
System.out.println(product.getStatus());


return new StockResponse(product.getOrderId(), product.getStatus());

}

private StockResponse findOrder(String id) {
return stocktList.stream()
.filter(user -> user.getOrderId()
.equals(id))
.findFirst()
.orElse(null);
}


}

当我调用 localhost:8082/stocks/order1 时,我得到的响应只有一个字段显示如下 enter image description here

我会错过什么?

最佳答案

我无法重现这个,这意味着它对我有用。

列出所有股票

$ curl -sS 'http://localhost:8080/stocks/' | jq "."
[
{
"orderId": "order1",
"status": "AVAILABLE"
},
{
"orderId": "order2",
"status": "AVAILABLE"
},
{
"orderId": "order3",
"status": "NOT AVAILABLE"
},
{
"orderId": "order4",
"status": "AVAILABLE"
}
]

获取特定库存

$ curl -sS 'http://localhost:8080/stocks/order1' | jq "."
{
"orderId": "order1",
"status": "AVAILABLE"
}

我的 StockController 与您的相同。我还复制并粘贴了您的 StockResponse 以获得与您相同的字段名称,但由于您没有包含构造函数/getter 和 setter,我将展示适合我的那个。

您在 stocktList 列表中实例化 StockResponse 对象的方式是使用构造函数,这可能表明您实际上并未设置 对象上的 this.status。如果这不起作用,请仔细检查状态字段的 getter 是否实际调用了 getStatus()

public class StockResponse {

private String orderId;
private String status;

public StockResponse(String orderId, String status) {
this.orderId = orderId;
this.status = status;
}

public String getOrderId() {
return orderId;
}

public void setOrderId(String orderId) {
this.orderId = orderId;
}

public String getStatus() {
return status;
}

public void setStatus(String status) {
this.status = status;
}
}

您的回复包含一个首字母使用“非标准”大写的字段这一事实告诉我,您可能正在做其他不标准的事情,这可能会影响您的结果。

关于json - json 响应 spring boot 中缺少字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63994084/

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