【问题标题】:Why am I getting a null value while hitting this api?为什么我在点击这个 api 时得到一个空值?
【发布时间】:2023-01-01 22:49:39
【问题描述】:

这是我的控制器:

@RestController
public class TransactionController {
    
    @Autowired
    TransactionService transactionService;
    
    @PostMapping("/add-transaction")
    public Transaction addTransaction(@RequestBody CustomerTransactions customerTransactions) {
        System.out.println("Check in controller");
        System.out.println(customerTransactions);
        return transactionService.addTransaction(customerTransactions);
    }

}

但 customerTransactions 为空。我通过以下方式在 Postman 中发送 JSON 请求:


{
    "Customer":{
        "custName": "Bikash Bhattarai",
        "email": "bksbhattarai@gmail.com",
        "phone": 9818122018
    },
    "Transaction":{
        "custId": "446bdfd3-3d09-43e7-83df-1883f967d296",
        "transdate": "03-04-2023",
        "transamount": 2000
    }
}

这是控制台输出:

Check in controller
CustomerTransactions [customer=null, transaction=null]
here we go
CustomerTransactions [customer=null, transaction=null]
null
2023-01-01T20:07:08.514+05:45 ERROR 14976 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: java.lang.NullPointerException: Cannot invoke "com.rewardsystem.AugustStore.entities.Customer.getCustId()" because "customer" is null] with root cause

【问题讨论】:

  • 提供CustomerTransactions类的结构。从@RequestBody 获取null 意味着无法完成从 JSON 到您的 POJO 类的对象映射,因为 JSON 的结构和您的 POJO 类 CustomerTransactions 不匹配。
  • public class CustomerTransactions { private Customer 客户;私人交易交易; public CustomerTransactions() { super(); // TODO 自动生成的构造函数存根 }
  • @BibekBhattarai 请edit 帖子并将此代码添加到帖子中。它在 cmets 中不可读。

标签: java spring api postman


【解决方案1】:

看起来 getter 和 setter 方法在客户交易,顾客交易类。请添加 getter/setter 方法并重试。

【讨论】:

    【解决方案2】:

    确保您的 CustomerTransactions 对象具有正确的字段并且它们被正确设置。如果任何字段为空,则在尝试将对象序列化为 JSON 时可能会导致问题。

    检查请求标头以确保它们包含 Content-Type: application/json 标头。这是服务器将请求正文正确解析为 JSON 所必需的。

    确保请求正文的格式正确 JSON。您可以使用 JSONLint 之类的工具来验证 JSON 并检查是否存在任何语法错误。

    如果您使用 REST 客户端来测试您的 API,请确保您将请求作为 POST 请求而不是 GET 请求发送。

    如果您仍然遇到问题,请尝试在您的代码中添加一些日志语句,以查看在执行过程中的不同点发生了什么。这可以帮助您确定问题发生的位置。

    【讨论】:

      猜你喜欢
      • 2021-06-24
      • 2021-04-11
      • 2016-09-26
      • 1970-01-01
      • 2015-07-25
      • 1970-01-01
      • 1970-01-01
      • 2023-01-12
      • 1970-01-01
      相关资源
      最近更新 更多