【问题标题】:Receive an urlenconded in Spring Boot API在 Spring Boot API 中接收 urlenconded
【发布时间】:2020-11-27 15:45:05
【问题描述】:

我需要从第三方 API 接收来自 webhook 的请求。

帖子内容为以下格式:

event=invoice.created&data%5Bid%5D=value1&data%5Bstatus%5D=pending&data%5Baccount_id%5D=value2

问题是用这些方括号序列化这个参数 data[id]。我在 Spring Boot 中遇到错误:

bean 类 [br.com.bettha.domain.dto.IuguWebhookDto] 的无效属性 'data[account_id]':索引属性路径 'data[account_id]' 中引用的属性既不是数组也不是 List 也不是 Map ;返回值为 [IuguDataDto(id=null, account_id=null, status=null, subscription_id=null)]

我的控制器:

@PostMapping(value = "/subscription-invoice", consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
@ApiOperation(
        value="Create a subscription invoice from Iugu's webhook",
        response= Invoice.class,
        notes="This Operation creates a subscription invoice from Iugu's webhook")
@PreAuthorize("#oauth2.hasScope('read')")
public ResponseEntity<Invoice> createSubscriptionInvoice(IuguWebhookDto iuguWebhookDto) {
    try {
        Invoice invoice = paymentService.createSubscriptionInvoiceFromIugusWebhook(iuguWebhookDto);
        return new ResponseEntity<>(invoice, HttpStatus.CREATED);
    } catch (EntityNotFoundException e) {
        throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage(), e);
    } catch (Exception e) {
        throw new ResponseStatusException(HttpStatus.INTERNAL_SERVER_ERROR, e.getMessage(), e);
    }
}

IuguWebhookDto.java:

@Getter
@Setter
@NoArgsConstructor
@ToString
public class IuguWebhookDto implements Serializable {
    private static final long serialVersionUID = -5557936429069206933L;

    private String event;
    
    private IuguDataDto data;

IuguDataDto.java:

@Getter
@Setter
@NoArgsConstructor
@ToString
public class IuguDataDto implements Serializable {
    private static final long serialVersionUID = -5557936429069206933L;

    private String id;

    private String account_id;

    private String status;

    private String subscription_id;

如何在 Spring Boot 中将这些请求参数作为对象接收?

【问题讨论】:

  • 很确定应该是 data.id, data.account_id, data.status, ... 而不是 data[id], data[account_id], data[status], ...跨度>
  • @NyamiouTheGaleanthrope,但不幸的是,事实并非如此。第二个API文档,post内容为data[id]等dev.iugu.com/docs/referencias-gatilhos。我无权更改 API 实现。它是第三方API,那么我需要知道是否有办法在Spring Boot中以这种格式获取这些值。

标签: java spring-boot webhooks


【解决方案1】:

我在使用 Iugu Webhooks API 时遇到了同样的问题。为了解决,我只是对 Iugu 发送的原始数据进行字符串化,删除不需要的字符,然后再次解析对象以获得我想要的变量。

    var dataReceived = JSON.stringify(req.body).replace('data[id]','id').replace('data[status]','status').replace('data[account_id]','account_id');

  var finalData = JSON.parse(dataReceived);

  return res.status(200).send(finalData.id);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-04-21
    • 2021-01-13
    • 2017-07-17
    • 2021-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-23
    相关资源
    最近更新 更多