JSON响应春季启动中缺少字段

时间:2020-09-21 14:13:45

标签: json spring-boot postman restapi get-mapping

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

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

我可能会错过什么?

1 个答案:

答案 0 :(得分:1)

我无法复制它,这意味着它对我有用。

列出所有股票

$ 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,以获得与您的字段名称相同的字段名称,但是由于您不包含构造函数/获取器和设置器,因此我将展示适合我的字段。

StockResponse列表中实例化stocktList对象的方式是使用构造函数,这可能表明您实际上没有在对象上设置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;
    }
}

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