JSON to XML policy

About | Samples | Element reference | Usage notes | Error codes | Related topics

What

This policy converts messages from the JavaScript Object Notation (JSON) format to extensible markup language (XML), giving you several options for controlling how messages are converted.

The policy is particularly useful if you want to transform messages using XSL. After converting a JSON payload to XML, use the XSL Transform policy with a custom style sheet to perform the transformation you need.

Where

This policy can be attached in the following locations.

ProxyEndpoint TargetEndpoint
    PreFlow Flow PostFlow PreFlow Flow PostFlow    
Request    
    Response
    PostFlow Flow PreFlow PostFlow Flow PreFlow    

Assuming that the intent is to convert a JSON-formatted request into an XML-formatted request, the policy would be attached to a request Flow (for example, Request / ProxyEndpoint / PostFlow).

Samples

<JSONToXML name="jsontoxml">
    <Source>request</Source>
    <OutputVariable>request</OutputVariable>
</JSONToXML>

This configuration takes JSON-formatted request message as the source, and then creates an XML-formatted message that is populated in the request OutputVariable. Edge automatically uses the content of this variable as the message for next processing step.


Element reference

Following are elements and attributes you can configure on this policy.

<JSONToXML async="false" continueOnError="false" enabled="true" name="JSON-to-XML-1">
    <DisplayName>JSON to XML 1</DisplayName>
    <Source>request</Source>
    <OutputVariable>request</OutputVariable>
    <Options>
        <NamespaceBlockName>#namespaces</NamespaceBlockName>
        <DefaultNamespaceNodeName>$default</DefaultNamespaceNodeName>
        <NamespaceSeparator>:</NamespaceSeparator>
        <AttributeBlockName>#attrs</AttributeBlockName>
        <AttributePrefix>@</AttributePrefix>
        <ArrayRootElementName>Array</ArrayRootElementName>
        <ArrayItemElementName>Item</ArrayItemElementName>
        <TextNodeName>#text</TextNodeName>
        <NullValue>I_AM_NULL</NullValue>
        <InvalidCharsReplacement>_</InvalidCharsReplacement>
    </Options>
</JSONToXML>

<JSONToXML> attributes

Attribute Description Default Presence
async

Set to true to specify that the policy should be run in a thread pool different than the pool servicing the request/response flow. Default is false.

Note: This setting is only used for for internal optimization. Contact Apigee support at the Support Portal for more information.

false Optional
continueOnError

Most policies are expected to return an error when a failure occurs (for example, when a Quota is exceeded). By setting this attribute to true, Flow execution continues on failure.

false Optional
enabled Determines whether a policy is enforced or not. If set to false, a policy is 'turned off', and not enforced (even though the policy remains attached to a Flow). true Optional
name

The internal name of the policy. Characters you can use in the name are restricted to: A-Z0-9._\-$ %. However, the Edge management UI enforces additional restrictions, such as automatically removing characters that are not alphanumeric.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

N/A Required

Schemas

See our GitHub repository samples for the most recent schemas.

<DisplayName> element

A natural-language name that labels the policy in the management UI proxy editor. If omitted, the policy name attribute is used.

<DisplayName>Custom label used in UI</DisplayName>
Default Policy name attribute value.
Presence Optional
Type String

<Source> element

The variable, request or response, that contains the JSON message that you want to convert to XML.

The HTTP Content-type header of the source message must be set to application/json, otherwise the policy is not enforced.

If <Source> is not defined, then it is treated as message (which resolves to request when the policy is attached to a request flow, or response when the policy is attached to a response flow).

If the source variable cannot be resolved, or resolves to a non-message type, the policy throws an error.

<Source>request</Source>
Default request or response, determined by where the policy is added to the API proxy flow
Presence Optional
Type message

<OutputVariable> element

Stores the output of the JSON to XML format conversion. This is usually the same value as the source, that is, usually a JSON request is converted to an XML request.

The payload of the JSON message is parsed and converted into XML, and the HTTP Content-type header of the XML-formatted message is set to application/xml.

If OutputVariable is not specified, the source is treated as OutputVariable. For example, if the source is request, then OutputVariable defaults to request.

<OutputVariable>request</Response>
Default request or response, determined by where the policy is added to the API proxy flow
Presence Optional
Type message

<Options>/<NamespaceBlockName>
<Options>/<DefaultNamespaceNodeName>
<Options>/<NamespaceSeparator> elements

JSON has no support for namespaces, while XML documents often require them. The NamespaceBlockName enables you to define a JSON property that serves as the source of a namespace definition in the XML that is produced by the policy. (This means that the source JSON must provide a property that can be mapped into a namespace that is expected by application that consumes the resulting XML.)

For example, the following settings:

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

indicates that a property called #namespaces exists in the source JSON that contains at least one namespace designated as the default. For example:

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

converts to:

<person xmlns="http://www.w3.org/1999/people" xmlns:exp="http://www.w3.org/1999/explorers">
  <person>John Smith</person>
  <exp:person>Pedro Cabral</exp:person>
</person>

<Options>/<AttributeBlockName>
<Options>/<AttributePrefix> elements

<AttributeBlockName> enables you to specify when JSON elements are converted into XML attributes (rather than XML elements).

For example, the following setting converts properties inside an object named #attrs into XML attributes:

<AttributeBlockName>#attrs</AttributeBlockName>

The following JSON object:

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

is converted to the following XML structure:

<person firstName="John" lastName="Smith">
  <occupation>explorer</occupation>
</person>

<AttributePrefix> converts the property starting with the specified prefix into XML attributes. Where the attribute prefix is set to @, for example:

<AttributePrefix>@</AttributePrefix>

Converts the following JSON object:

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

 }
}

to the following XML structure:

<person firstName="John" lastName="Smith">
  <occupation>explorer</occupation>
</person>

<Options>/<ArrayRootElementName>
<Options>/<ArrayItemElementName> element

Converts a JSON array into a list of XML elements with specified parent and child element names.

For example, the following settings:

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

converts the following JSON array:

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

into the following XML structure:

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

<Options>/<TextNodeName> element

Converts a JSON property into an XML text node with the specified name. For example, the following setting:

<TextNodeName>age</TextNodeName>

converts this JSON:

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

to this XML structure:

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

If TextNodeName is not specified, the XML is generated, using the default setting for a text node:

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

<Options>/<NullValue> element

Indicates a null value. By default the value is NULL.

For example the following setting:

<NullValue>I_AM_NULL</NullValue>
Converts the following JSON object:
{"person" : "I_AM_NULL"}

to the following XML element:

<person></person>

Where no value (or a value other than I_AM_NULL) is specified for the Null value, then the same payload converts to:

<person>I_AM_NULL</person>

<Options>/<InvalidCharsReplacement> element

To assist with handling invalid XML that may cause issues with a parser, this setting replaces any JSON elements that produce invalid XML with the string. For example, the following setting:

<InvalidCharsReplacement>_</InvalidCharsReplacement>

Converts this JSON object

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

to this XML structure:

<First_Name>John<First_Name>

Usage notes

In a typical mediation scenario, a JSON to XML policy on the inbound request flow is often paired with an XMLtoJSON policy on the outbound response flow. By combining policies this way, a JSON API can be exposed for services that natively support only XML.

It is often useful to apply the default (empty) JSON to XML policy and iteratively add configuration elements as required.

For scenarios where APIs are consumed by diverse clients apps which may require either JSON and XML, the format of the response can be dynamically set by configuring JSON to XML and XML to JSON policies to execute conditionally. See Flow variables and conditions for an implementation of this scenario.

Error codes

The default format for error codes returned by Policies is:

{
  "code" : " {ErrorCode} ",
  "message" : " {Error message} ",
  "contexts" : [ ]
}

The JSON to XML Policy type defines the following error codes:

Error Code Message
SourceUnavailable JSONToXML[{0}]: Source {1} is not available
ExecutionFailed JSONToXML[{0}]: Execution failed due to reason: {1}
OutputVariableIsNotAvailable JSONToXML[{0}]: Output variable is not available.
InCompatibleTypes JSONToXML[{0}]: String can not be assigned to message type.
InvalidSourceType JSONToXML[{0}]: Invalid source type {0}. Valid source types are {1}.

Related topics

For working samples of API proxies, see the Samples reference.

 

Help or comments?

  • Something's not working: See Apigee Support
  • Something's wrong with the docs: Click Send Feedback in the lower right.
    (Incorrect? Unclear? Broken link? Typo?)