This documentation is for WSO2 Enterprise Service Bus version 5.0.0. For the latest ESB, view the latest WSO2 Enterprise Integrator documentation.

All docs This doc

Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Table of Contents
maxLevel3

Anchor
MessageBuildersandFormatters
MessageBuildersandFormatters
JSON message builders and formatters

The ESB provides two types of message builders and formatters for JSON. The default builder and formatter keep the JSON representation intact without converting it to XML. You can access the payload content using JSON Path or XPath and convert the payload to XML at any point in the mediation flow.

...

Note

Always use the same type of builder and formatter combination. Mixing different builders and formatters will cause errors at runtime.

Tip

If you want the ESB to handle JSON payloads that are sent using a media type other

...

than application/json, you must register the JSON builder and formatter for that media type in the following two files at minimum (for best results, register them in all Axis2 configuration files found in

...

the <ESB_HOME>/repository/conf/axis2

...

 directory):

  • <ESB_HOME>/repository/conf/axis2/axis2.xml
  • <ESB_HOME>/repository/conf/axis2/axis2_blocking_client.xml

For example, if the media type

...

is text/javascript, register the message builder and formatter as follows:

Code Block
languagehtml/xml
<messageBuilder contentType="text/javascript" 
               class="org.apache.synapse.commons.json.JsonStreamBuilder"/>

<messageFormatter contentType="text/javascript" 
                class="org.apache.synapse.commons.json.JsonStreamFormatter"/> 
Note

When you modify the builders/formatters in Axis2 configuration, make sure that you have enabled only one correct message builder/formatter pair for a given media type.

...

Code Block
languagehtml/xml
<property name="messageType" value="application/json" scope="axis2"/>
Infonote

JSON requests cannot be converted to xml XML if it contains invalid xml XML characters. 

Accessing content from JSON payloads

There are two ways to access the content of a JSON payload within the ESB.

  • JSONPath expressions (with json-eval() method)

  • XPath expressions

JSONPath allows you to access fields of JSON payloads with faster results and less processing overhead. Although it is possible to evaluate XPath expressions on JSON payloads by assuming the XML representation of the JSON payload, we recommend that you use JSONPath to query JSON payloads. It is also possible to evaluate both JSONPath and XPath expressions on a payload (XML/JSON) at the same time.

You can use JSON path expressions with following mediators:

...

As a log property:

Code Block
languagehtml/xml
<log>
    <property name="location" 
              expression="json-eval($.coordinates.location[0].name)"/>
</log>

...

As a standalone property:

...

languagehtml/xml

...

Info

If you need to convert complex XML responses (e.g., XML with with xsi:type values), you will need to set the message type using the Property mediator as follows:

<property name="messageType" value="application/json/badgerfish" scope="axis2" type="STRING"/>

You will also need to ensure you register the following message builder and formatter as specified in Message Builders and Formatters.

Code Block
languagexml
<messageBuilder contentType="text/javascript" 
               

...

class="

...

As the payload arguments:

...

languagehtml/xml

...

org.apache.axis2.json.JSONBadgerfishOMBuilder"/>

<messageFormatter contentType="text/javascript" 
     

...

         

...

 

...

 

...

class="

...

org.apache.

...

axis2.json.JSONBadgerfishMessageFormatter"/>

...

 

...

Accessing content from JSON payloads

There are two ways to access the content of a JSON payload within the ESB.

  • JSONPath expressions (with json-eval() method

...

  • )

  • XPath expressions

JSONPath allows you to access fields of JSON payloads with faster results and less processing overhead. Although it is possible to evaluate XPath expressions on JSON payloads by assuming the XML representation of the JSON payload, we recommend that you use JSONPath to query JSON payloads. It is also possible to evaluate both JSONPath and XPath expressions on a payload (XML/JSON) at the same time.

You can use JSON path expressions with following mediators:

MediatorUsage
Log

As a log property:

Code Block
languagehtml/xml
<switch source
<log>
    <property name="location" 
              expression="json-eval($.coordinates.location[0].name)"/>
</log>
Filter
Property

As

the filter source

a standalone property:

Code Block
languagehtml/xml
<filter
<property 
source
name=
"json-
"location" 
              expression="json-eval($.coordinates.location[0].name)"
regex="Eiffel.*">

JSON path syntax

...

/>
PayloadFactory  

As the payload arguments:

Code Block
language

...

html/xml
<payloadFactory media-type="json">
    <format>{"

...

RESPONSE":

...

"

...

$1"}</format>
  

...

 

...

 

...

<args>

...

 

...

 

...

 

...

 

...

 

...

 

...

  <arg evaluator="

...

json"

...

The following table summarizes sample JSONPath expressions and their outputs:

ExpressionResult
$.
{ "id":12345, "id_str":"12345", "array":[
 expression="$.coordinates.location[0].name"/>
    </args>
</payloadFactory>

IMPORTANT: You MUST omit the json-eval() method within the payload arguments to evaluate JSON paths within the PayloadFactory mediator. Instead, you MUST select the correct expression evaluator (xml or json) for a given argument.

Switch

As the switch source:

Code Block
languagehtml/xml
<switch source="json-eval($.coordinates.location[0].name)">
Filter

As the filter source:

Code Block
languagehtml/xml
<filter source="json-eval($.coordinates.location[0].name)" 
        regex="Eiffel.*">

JSON path syntax

Suppose we have the following payload:

Code Block
languagejavascript
{ 
  "id": 12345,
  "id_str": "12345",
  "array": [ 1, 2, [ [], [{"inner_id": 6789}] ] ],
  "name": null,
  "object": {},
  "$schema_location": "unknown",
  "12X12": "image12x12.png"
}

...

$.id

...

12345

...

$.name

...

The following table summarizes sample JSONPath expressions and their outputs:

ExpressionResult
$.
object
{}
$.['$schema_location']
unknown
$.12X12
image12x12.png
$.array
{ "id":12345, "id_str":"12345", "array":[1, 2, [[],[{"inner_id":6789}]]]
$.array[2][1][0].inner_id
6789

You can learn more about JSONPath syntax here.

Logging JSON payloads

To log JSON payloads as JSON, use the Log mediator as shown below. The json-eval() method returns the java.lang.String representation of the existing JSON payload.

...

, "name":null, "object":{}, "$schema_location":"unknown", "12X12":"image12x12.png"}
$.id
12345
$.name
null
$.object
{}
$.['$schema_location']
unknown
$.12X12
image12x12.png
$.array
[1, 2, [[],[{"inner_id":6789}]]]
$.array[2][1][0].inner_id
6789

You can learn more about JSONPath syntax here.

Logging JSON payloads

To log JSON payloads as JSON, use the Log mediator as shown below. The json-eval() method returns the java.lang.String representation of the existing JSON payload.

Code Block
languagehtml/xml
<log>
    <property name="JSON-Payload" expression="json-eval($.)"/>
</log>

...

XML to JSON transformation parameters

You can use XML to JSON transformation parameters add the parameters listed below to the synapse.properties file (stored in the <ESB_HOME>/repository/conf/ directory) when you need to transform XML formatted data into the JSON format.Following are the XML to JSON transformation parameters and their descriptions:

Parameter

Description

Default Value

synapse.commons.json.preserve.namespace

Preserves the namespace declarations in the JSON output in XML to JSON transformations.

false

synapse.commons.json.buildValidNCNames

Builds valid XML NCNames when building XML element names in XML to JSON transformations.

false

synapse.commons.json.output.autoPrimitive

Allows primitive types in the JSON output in XML to JSON transformations.

true

synapse.commons.json.output.namespaceSepChar

The namespace prefix separation character for the JSON output in XML to JSON transformations.

The default separation character is -

synapse.commons.json.output.enableNSDeclarations

Adds XML namespace declarations in the JSON output in XML to JSON transformations.

false

synapse.commons.json.output.disableAutoPrimitive.regex

Disables auto primitive conversion in XML to JSON transformations.

null

synapse.commons.json.output.jsonoutAutoArray

Sets the JSON output to an array element in XML to JSON transformations.

true

synapse.commons.json.output.jsonoutMultiplePI

Sets the JSON output to an xml multiple processing instruction in XML to JSON transformations.

true

synapse.commons.json.output.xmloutAutoArray

Sets the XML output to an array element in XML to JSON transformations.

true

synapse.commons.json.output.xmloutMultiplePI

Sets the XML output to an xml multiple processing instruction in XML to JSON transformations.

synapse.commons.json.output.emptyXmlElemToEmptyStr

Sets an empty element to an empty JSON string in XML to JSON transformations.
false

Anchor
troubleshooting
troubleshooting

Validating JSON messages

You can use the Validate mediator to validate JSON messages against a specified JSON schema as described in the rest of this section.

Validate mediator

The parameters available in this section are as follows.

Parameter NameDescription
Schema keys defined for Validate MediatorThis section is used to specify the key to access the main schema based on which validation is carried out, as well as to specify the JSON, which needs to be validated. 
SourceThe JSONPath expression to extract the JSON that needs to be validated. E.g: json-eval($.msg)"

Following example use the below sample schema  StockQuoteSchema.json file. Add this sample schema file (i.e. StockQuoteSchema.json) to the following Registry path:  conf:/schema/StockQuoteSchema.json. For instructions on adding the schema file to the Registry path, see Adding a Resource.

Tip

When adding this sample schema file to the Registry, specify the Media Type as application/json.

Code Block
languagejava
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "getQuote": {
      "type": "object",
      "properties": {
        "request": {
          "type": "object",
          "properties": {
            "symbol": {
              "type": "string"
            }
          },
          "required": [
            "symbol"
          ]
        }
      },
      "required": [
        "request"
      ]
    }
  },
  "required": [
    "getQuote"
  ]
}
 

In this example, the required schema for validating messages going through the Validate mediator is given as a registry key (i.e. schema\StockQuoteSchema.json). You do not have any source attributes specified. Therefore, the schema will be used to validate the complete JSON body. The mediation logic to follow if the validation fails is defined within the on-fail element. In this example, the PayloadFactory mediator creates a fault to be sent back to the party, which sends the message.

Code Block
languagejava
<validate>
    <schema key="conf:/schema/StockQuoteSchema.json"/>
    <on-fail>
        <payloadFactory media-type="json">
            <format>{"Error":$1"}</format>
            <args>
                <arg evaluator="xml" expression="$ctx:ERROR_MESSAGE"/>
            </args>
        </payloadFactory>
        <property name="HTTP_SC" value="500" scope="axis2"/>
        <respond/>
    </on-fail>
</validate>

An example for a valid JSON payload request is given below.

Code Block
languagejava
{
   "getQuote": {
      "request": {
         "symbol": "WSO2"
      }
   }
}

Troubleshooting, debugging, and logging

...