Tomasz
Tomasz

Reputation: 61

Transforming JSON array with WSO2

Do we have some idea how Transforming json with array for new json with another fields. I have example json. This sample json is dynamic. Can have three or four elements in array.

"insurer": [ 
     {
    "data": {
        "first_name": "Name",
        "last_name": "SureName"
    }
    },
   {
    "data": {
        "first_name": "Name1",
        "last_name": "SureName1"
    }
}],

And I'd like receive json

    "insurer": [ 
     {
    "data": {
        "name": "Name",
        "nameLast": "SureName"
    }
    },
   {
    "data": {
        "name": "Name1",
        "nameLast": "SureName1"
    }
}],

I did this sequence

 <foreach id="foreach_1" expression="//insurer/data">
        <sequence>
           <payloadFactory media-type="json">
              <format>{ "name" : "$1", 
                        "nameLast" : "$2"                            }                  
              </format>
              <args>
                 <arg evaluator="xml" expression="//first_name"/>
                 <arg evaluator="xml" expression="//last_name"/>
              </args>
           </payloadFactory>
           <log>
              <property name="message" value="petla"/>
           </log>
        </sequence>
     </foreach>

Unfortunately, I'm only getting a partial json. You may have an idea

 { ,"name" : "Name1", "nameLast" : "SureName1" }

I'm using WSO2 ESB V6.1.0

Upvotes: 1

Views: 1515

Answers (1)

With 3 changes to your sequence, this should work as expected.

  1. First change the expression of the foreach modiator to //insurer, since your JSON message has array for insurer.
  2. Next, use XML as the media-type of the payload factory mediator and compose a single expected insurer element.
  3. Finally set messageType property to change the message type to JSON.

Find sample code below.

     <foreach xmlns:ns="http://org.apache.synapse/xsd"
              expression="//insurer">
        <sequence>
           <payloadFactory media-type="xml">
              <format>
                <insurer>
                   <data>
                      <name>$1</name>
                      <nameLast>$2</nameLast>
                   </data>
                </insurer>
              </format>
              <args>
                 <arg evaluator="xml" expression="//first_name"/>
                 <arg evaluator="xml" expression="//last_name"/>
              </args>
           </payloadFactory>
        </sequence>
     </foreach>
     <property name="messageType" value="application/json" scope="axis2"
               type="STRING"/>

Upvotes: 2

Related Questions