JSONtoXML 政策

<ph type="x-smartling-placeholder"></ph> 您正在查看 Apigee Edge 文档。
转到 Apigee X 文档
信息

内容

此政策会将消息从 JavaScript 对象表示法 (JSON) 格式转换为可扩展标记语言 (XML),并提供多个控制邮件转换方式的选项。

此政策特别适用于您想使用 XSL 转换消息的情况。将 JSON 载荷转换为 XML 后,在样式表中使用 XSL 转换政策来执行所需的转换。

假设意图是将 JSON 格式的请求转换为 XML 格式的请求,则政策将附加到请求流(例如,请求/ProxyEndpoint/PostFlow)。

示例

有关在 JSON 和 XML 之间进行转换的详细讨论,请参阅 http://community.apigee.com/articles/1839/converting-between-xml-and-json-what-you-need-to-k.html

转换请求

<JSONToXML name="jsont>oxml&<quot;
>    Sou<rcerequ>est/S<ource
    Outp>utVaria<blerequest/Outp>u<tVariable
>/JSONToXML

此配置接受 JSON 格式的请求消息作为来源,然后创建在 request OutputVariable 中填充的 XML 格式消息。边缘 并自动将此变量的内容用作下一个处理步骤的消息。


元素参考

下面是您可以在此政策中配置的元素和属性。

<JSONToXML async="false" continueOnError="false" enabled="t>rue&q<uot; name=&>quot;JSON-to-<XML-1"<>/span>
    D<isplay>NameJSO<N to XM>L 1/D<isplayName
   > Source<request/Source
>    O<utputVa>riablereq<uest/OutputVariabl>e
   < Options
        Om>itXmlDecl<arationfalse/OmitXmlDecl>aration
<        DefaultNamespaceN>odeName$d<efault/DefaultName>s<paceNodeName
      >  Namespa<ceSeparator:/Names>paceSe<parator
        Att>ributeBlo<ckName#attrs/At>t<ributeBlockName<>/span>
        A<ttributePrefix@/Attri>bute<Prefix
        ObjectR>ootElemen<tNameRoot/ObjectRoot>Eleme<ntName
        ArrayR>ootElemen<tNameArray/ArrayRoot>Elem<entName
        Array>ItemEleme<ntName>Item/<ArrayIt>emElement<Name
       > Inde<ntfalse/Inden>t
       < TextNode>Name#text</TextNodeN>ame
     <   NullValueI_AM_NULL/N>u<llValue
        InvalidC>harsR<eplaceme>n<t_/Invalid>CharsReplacement
    /Options
/JSONToXML

<JSONToXML> 属性

下表介绍了所有政策父元素通用的特性:

属性 说明 默认 状态
name

政策的内部名称。name 属性的值可以包含字母、数字、空格、连字符、下划线和英文句点。此值不能超过 255 个字符。

(可选)使用 <DisplayName> 元素在管理界面代理编辑器中给政策添加不同的自然语言名称标签。

不适用 必填
continueOnError

设置为 false 可在政策失败时返回错误。这是大多数政策的预期行为。

设置为 true,即使在政策失败后,仍可以继续执行流。

false 可选
enabled

设置为 true 可强制执行政策。

设为 false关闭政策。即使政策仍附加到某个流,也不会强制执行该政策。

可选
async

此特性已弃用。

false 已弃用

<DisplayName> 元素

除了用于 name 属性之外,还可以用于在管理界面代理编辑器中给政策添加不同的自然语言名称标签。

<DisplayName>Policy Display Name</DisplayName>
默认

不适用

如果省略此元素,则会使用政策的 name 属性的值。

状态 可选
类型 字符串

<Source> 元素

包含要转换为 XML 的 JSON 消息的变量、请求或响应。

如果未定义 <Source>,则系统会将其视为消息(当政策附加到请求流时解析为请求,或者在政策附加到响应流时响应)。

如果源变量无法解析或解析为非消息类型,则政策会提示错误。

<Source>request</Source>
默认 请求或响应,由将政策添加到 API 代理流的位置决定。
状态 可选
Type 消息

<OutputVariable> 元素

存储 JSON 到 XML 格式转换的输出。这通常与来源值相同,即通常将 JSON 请求转换为 XML 请求。

JSON 消息的载荷将被解析并转换为 XML,并将 XML 格式的消息的 HTTP Content-type 标头设置为 text/xml;charset=UTF-8

如果未指定 OutputVariable,则 source 将被视为 OutputVariable。例如,如果 sourcerequest,则 OutputVariable 默认为 request

<OutputVariable>request</OutputVariable>
默认 请求或响应,由将政策添加到 API 代理流的位置决定。
状态 如果 <Source> 元素中定义的变量为字符串类型,则此元素是必填的。
Type 消息

<Options>/<OmitXmlDeclaration>

指定从输出中省略 XML 命名空间。默认值为 false,表示输出中包含命名空间。

例如,以下设置会将政策配置为省略命名空间:

<OmitXmlDeclaration>true</OmitXmlDeclaration>

<Options>/<NamespaceBlockName>
<Options>/<DefaultNamespaceNodeName>
<Options>/<NamespaceSeparator> 元素

JSON 不支持命名空间,而 XML 文档通常需要这些命名空间。NamespaceBlockName 让您可定义 JSON 属性,将其作为政策生成的 XML 中的命名空间定义来源。(这意味着来源 JSON 必须提供一个属性,该属性可以映射到使用生成的 XML 的应用所需的命名空间。)

例如,以下设置:

<NamespaceBlockName>#namespaces</NamespaceBlockName>
<DefaultNamespaceNodeName>$default</DefaultNamespaceNodeName>
<NamespaceSeparator>:</NamespaceSeparator>

表示来源 JSON 中存在名为 #namespaces 的属性,它至少包含一个指定为默认值的命名空间。例如:

{
   "population": {
       "#namespaces": {
           "$default": "http://www.w3.org/1999/people",
           "exp": "http://www.w3.org/1999/explorers"
       },
       "person": "John Smith",
       "exp:person": "Pedro Cabral"
   }
}

转换为:

<population xmlns="http://www.w3.org/1999/people" xmlns:exp="http://www.w3.org/>199<9/expl>orers"<;
  per>son<John Smith>/person
  ex<p:personPed>r<o Cabral/ex>p:person
/population

<Options>/<ObjectRootElementName>

<ObjectRootElementName> 指定从 JSON(不含已命名的根元素)转换为 XML 时的根元素名称。

例如,如果 JSON 显示为:

{
  "abc": "123",
  "efg": "234"
}

并将 <ObjectRootElementName> 设置为:

<ObjectRootElementName>Root</ObjectRootElementName>

生成的 XML 会显示为:

<Root>
   <abc>123</abc>
   <efg>234</efg>
</Root>

<Options>/<AttributeBlockName>
<Options>/<AttributePrefix> 元素

<AttributeBlockName> 让您可指定何时将 JSON 元素转换为 XML 属性(而不是 XML 元素)。

例如,以下设置会将名为 #attrs 的对象中的属性转换为 XML 属性:

<AttributeBlockName>#attrs</AttributeBlockName>

以下 JSON 对象:

{
    "person" : {
        "#attrs" : {
            "firstName" : "John",
            "lastName" : "Smith"
        },        
        "occupation" : "explorer",
    }
}

将转换为以下 XML 结构:

<person firstName="John" lastNa>me=<"Smit>h"
<  occupatio>n<explore>r/occupation
/person

<AttributePrefix> 会将以指定前缀开头的属性转换为 XML 属性。其中,将属性前缀设置为 @,例如:

<AttributePrefix>@</AttributePrefix>

转换以下 JSON 对象:

{
"person" : {
   "@firstName" : "John",
   "@lastName" : "Smith"
   "occupation" : "explorer",

 }
}

为以下 XML 结构:

<person firstName="John" lastNa>me=<"Smit>h"
<  occupatio>n<explore>r/occupation
/person

<Options>/<ArrayRootElementName>
<Options>/<ArrayItemElementName> 元素

将 JSON 数组转换为包含指定父元素和子元素名称的 XML 元素列表。

例如,以下设置:

<ArrayRootElementName>Array</ArrayRootElementName>
<ArrayItemElementName>Item</ArrayItemElementName>

转换以下 JSON 数组:

[
"John Cabot",
{
 "explorer": "Pedro Cabral"
},
"John Smith"
]

为以下 XML 结构:

<Array>
  <Item>John Cabot</Item>
  <Item>
    <explorer>Pedro Cabral</explorer>
  </Item>
  <Item>John Smith</Item>
</Array>

<Options>/<Indent>

指定缩进 XML 输出。默认值为 false,表示不缩进。

例如,以下设置会将政策配置为缩进输出:

<Indent>true</Indent>

如果 JSON 输入格式为:

{"n": [1, 2, 3] }

则没有缩进的输出为:

<Array><n>1</n><n>2</n><n>3</n></Array>

启用缩进后,输出为:

  <Array>
    <n>1</n>
    <n>2</n>
    <n>3</n>
  </Array>

<Options>/<TextNodeName> 元素

将 JSON 属性转换为具有指定名称的 XML 文本节点。例如,以下设置:

<TextNodeName>age</TextNodeName>

转换此 JSON:

{
    "person": {
        "firstName": "John",
        "lastName": "Smith",
        "age": 25
    }
}

为以下 XML 结构:

<person>
  <firstName>John</firstName>25<lastName>Smith</lastName>
</person>

如果未指定 TextNodeName,则使用文本节点的默认设置生成 XML:

<person>
  <firstName>John</firstName>
  <age>25</age>
  <lastName>Smith</lastName>
</person>

<Options>/<NullValue> 元素

表示 null 值。默认情况下,值为 NULL

例如,以下设置:

<NullValue>I_AM_NULL</NullValue>
转换以下 JSON 对象:
{"person" : &quot;I_AM_NULL"}

为以下 XML 元素:

<person></person>

如果未为 Null 值指定值(或 I_AM_NULL 以外的值),则相同的载荷将转换为:

<person>I_AM_NULL</person>

<Options>/<InvalidCharsReplacement> 元素

为了帮助处理可能引起解析器问题的无效 XML,此设置会使用字符串替换生成无效 XML 的任何 JSON 元素。例如,以下设置:

<InvalidCharsReplacement>_</InvalidCharsReplacement>

转换此 JSON 对象

{
    "First%%%Name": "John"
}

为以下 XML 结构:

<First_Name>John<First_Name>

使用说明

在典型的中介情景中,入站请求流中的 JSON 到 XML 政策通常与出站响应流上的 XMLtoJSON 政策配对。通过以这种方式合并政策,您可以针对原生仅支持 XML 的服务公开 JSON API。

将默认(空)JSON 应用于 XML 政策并根据需要以迭代方式添加配置元素通常会很有帮助。

对于可能需要 JSON 和 XML 的多种客户端应用使用 API 的情况,系统可以通过将 JSON 到 XML 和 XML 到 JSON 政策配置为有条件执行,动态设置响应的格式。如需了解此使用场景的实现情况,请参阅流变量和条件

架构

错误参考信息

This section describes the fault codes and error messages that are returned and fault variables that are set by Edge when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause Fix
steps.jsontoxml.ExecutionFailed 500 The input payload (JSON) is empty or the input (JSON) passed to JSON to XML policy is invalid or malformed.
steps.jsontoxml.InCompatibleTypes 500 This error occurs if the type of the variable defined in the <Source> element and the <OutputVariable> element are not the same. It is mandatory that the type of the variables contained within the <Source> element and the <OutputVariable> element matches. The valid types are message and string.
steps.jsontoxml.InvalidSourceType 500 This error occurs if the type of the variable used to define the <Source> element is invalid. The valid types of variable are message and string.
steps.jsontoxml.OutputVariableIsNotAvailable 500 This error occurs if the variable specified in the <Source> element of the JSON to XML Policy is of type string and the <OutputVariable> element is not defined. The <OutputVariable> element is mandatory when the variable defined in the <Source> element is of type string.
steps.jsontoxml.SourceUnavailable 500 This error occurs if the message variable specified in the <Source> element of the JSON to XML policy is either:
  • out of scope (not available in the specific flow where the policy is being executed) or
  • can't be resolved (is not defined)

Deployment errors

None.

Fault variables

These variables are set when a runtime error occurs. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name="fault_name" fault_name is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name Matches "SourceUnavailable"
jsontoxml.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. jsontoxml.JSON-to-XML-1.failed = true

Example error response

{
  "fault": {
    "faultstring": "JSONToXML[JSON-to-XML-1]: Source xyz is not available",
    "detail": {
      "errorcode": "steps.json2xml.SourceUnavailable"
    }
  }
}

Example fault rule

<FaultRule name="JSON To XML Faults">
    <Step>
        <Name>AM-SourceUnavailableMessage</Name>
        <Condition>(fault.name Matches "SourceUnavailable") </Condition>
    </Step>
    <Step>
        <Name>AM-BadJSON</Name>
        <Condition>(fault.name = "ExecutionFailed")</Condition>
    </Step>
    <Condition>(jsontoxml.JSON-to-XML-1.failed = true) </Condition>
</FaultRule>

相关主题