json 响应 spring 引导中缺少字段

field missing in the json response spring boot

我的 Stock 响应 class 只有两个字段如下

class StockResponse {

private String orderId;
private String status;

//constructor

//getters and setters

}

还有控制器如下

@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 时,我得到的响应只有一个字段显示如下

我会错过什么?

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

列出所有股票

$ 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 以获得与您相同的字段名称,但由于您没有包含 constructor/getter 和 setter,我将展示适合我的那个。

您在 stocktList 列表中实例化 StockResponse 对象的方式是使用构造函数,这可能表明您实际上并未在对象。如果这不起作用,请仔细检查状态字段的 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;
    }
}

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