Mule#4:RAML 无法解析转义字符中的 JSON

问题描述

我在 RAML 1.0 中声明了以下架构

body:
   application/json:
    type: object
                properties:
                  region:
                    example:
                      strict: false
                      value: NA
                    type: string
                    required: true
                  country:
                    description: Country name
                    example:
                      strict: false
                      value: US
                    type: string
                    required: true
                  orders:
                    type: array
                    items:
                      properties:
                        orderName:
                          example:
                            strict: false
                            value: "toys"
                          type: string
                          maxLength: 20
                          required: false
                        orderNumber:
                          example:
                            strict: false
                            value: order12
                          type: string
                          maxLength: 25
                          required: false
                    maxItems: 100
                    required: true

当我发送以下 JSON 请求时

{
    "region": "South America","country": "US","orders": [
        "{\n  \"orderNumber\": \"ORD0118\",\n  \"orderName\": \"toys\"\n}","{\n  \"orderNumber\": \"ORD0119\",\n  \"orderName\": \"pens\"\n}","{\n  \"orderNumber\": \"ORD0120\",\n  \"orderName\": \"pencils\"\n}"
    ]
}

当我批量聚合消息并连接有效负载时,有效负载的格式如上所示。 我看到一个错误的请求错误

Position: Line 0,Column 0\n/orders/0 expected type: JSONObject,found: String  Location:   Position: Line 0,Column 0\n/orders/1 expected type: JSONObject,Column 0\n/orders/2 expected type: JSONObject,Column 0",

请帮助我更新 RAML 以接受转义字符中的 JSON。

解决方法

有效载荷的 orders 属性是一个字符串列表,而不是对象列表,因为数组的成员是“转义”的。根据您打算做什么,您可以更改 RAML 以将数组设置为字符串数组,或者以某种方式将字符串转换为 RAML 期望的对象。

对于前者,将订单的定义替换为:

           orders:
                type: string[]

如果您想稍后执行以下操作,以下 DataWeave 脚本将转换预期对象中的列表:

%dw 2.0
output application/json
---
{
    region: payload.region,country: payload.country,orders: payload.orders map read($,"application/json")
}

输出:

{
  "region": "South America","country": "US","orders": [
    {
      "orderNumber": "ORD0118","orderName": "toys"
    },{
      "orderNumber": "ORD0119","orderName": "pens"
    },{
      "orderNumber": "ORD0120","orderName": "pencils"
    }
  ]
}
,

在批处理聚合器中启用保留 MIME 类型解决了这个问题。