使用 Mule 4 中所需的任一字段验证 json 数组

Validate the json Array with Either one field required in Mule 4

请求Json 如下所示:-

{ 
   "eNumber": 8506493,   
   "details": [
     {
      "id":12345,
      "name": xyz123
     }
  ]
}

作为要求的一部分,我需要检查 "id" 或 "name" 字段必须存在的 "details" 数组。如果存在 "id" 字段,则 "name" 是非强制性的。如果存在 "name" 字段,则 "id" 是非强制性的。如果不满足则抛出错误。

我尝试了几个选项,使用过滤详细信息数组并在验证组件中检查过滤后的数组的大小。它似乎运作不佳。如果有人变得更好 solutions.please 在这里分享。

如果通过您的条件

,此示例代码将 return 为真或为假
%dw 2.0
import * from dw::core::Arrays
output application/json
---
payload.details every ((item) -> item.id? or item.name?)

我使用的函数是 every,它检查数组中的所有元素是否都符合给定的条件。

稍后您可以使用一个选项,并使用带有 if else 的 raise error or you can use the fail dw 函数。

您可以在 RAML 级别对其进行限制。 示例 RAML -

#%RAML 1.0
title: api

types:
  test1:
      type: object
      properties:
        id: 
         type: string
         example: 123a
  test2:
    type: object
    properties:
      name: 
        type: string
        example: xyz124 
      
  test3:
      type: object
      properties:
        enumber: 
          type: string
          example: 8506493a
        details : 
         type: [test1 | test2]
/test:
  post:
    body:
      application/json:
        type: test3