---
schema_version: "1"
id: fb291ddede43a69951289d42e1b6e07606f9f2b8d2fa89c99c84fff0d10b0437
title: DataWeave を使用したフライトデータの変換
collection: mulesoft
version: current
locale: ja-jp
portal_url: https://docs.salesforce.com/mulesoft/current/ja-jp/anypoint-code-builder/tut-af-integrate-use-dataweave.md
canonical_url: https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-use-dataweave
source_site: docs.mulesoft.com
content_type: documentation
content_hash: 3e59aa062923d7df3141512341d00f6be317839b60141a2e8bfc1c5636ba3e28
description: MuleSoft Documentation Site
latest: true
---
# DataWeave を使用したフライトデータの変換

**進行中のベータリリース**​: **クラウド IDE は進行中のベータリリースです**​。ベータ状態での Anypoint Code Builder の使用には、IDE で入手できる、該当するベータサービス契約条件が適用されます。

DataWeave を使用してフライトデータを変換して API 仕様に一致させます。

## [](#始める前に)始める前に

次の手順を実行します。

1. [American Flights プロセスの統合](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-am-flights)
2. [アプリケーションからデータベースへの接続](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-connect-to-a-db)

## [](#snippets)変換用のユーザースニペットを作成する

`mule-xml.json`​ ファイルでスニペットを定義します。スニペットについての詳細は、[work-with-code-snippets.adoc](#work-with-code-snippets.adoc)を参照してください。

1. \[Configure Snippets (スニペットを制御)\] に移動します。
    
    手順を表示
    
    - デスクトップ IDE で、​**\[Code (コード)\]**​ > ​**\[Settings (設定)\]**​ > ​**\[Configure Snippets (スニペットを設定)\]**​ を選択する。
    - クラウド IDE で、​![](/mulesoft/current/ja-jp/anypoint-code-builder/_images/icon-menu.png)​ (メニュー) アイコンをクリックし、​**\[Preferences (プリファレンス)\]**​ > ​**\[Configure Snippets (スニペットを設定)\]**​ を選択する。
    - いずれかの IDE で次の操作を実行する。
        
        1. キーボードショートカットを使用してコマンドパレットを開く。
            
            - Mac: Cmd+Shift+p
            - Windows: Ctrl+Shift+p
        2. 次のコマンドを選択する。
            
            ```command
            Snippets: Configure Snippets
            ```
2. 開いた ​**\[Select Snippets File or Create Snippets (スニペットファイルを選択またはスニペットを作成)\]**​ 項目で、次を入力します。
    
    ```command
    mule-xml.json (Mule XML)
    ```
3. ファイルに設定が含まれていない場合、​`mule-xml.json`​ では、中括弧内にコメントが提供されます。
    
    ```json
    {
    	// Place your snippets for mule-xml here. Each snippet is defined under a snippet name and has a prefix, body and
    	// description. The prefix is what is used to trigger the snippet and the body will be expanded and inserted. Possible variables are:
    	// $1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders. Placeholders with the
    	// same ids are connected.
    	// Example:
    	// "Print to console": {
    	// 	"prefix": "log",
    	// 	"body": [
    	// 		"console.log('$1');",
    	// 		"$2"
    	// 	],
    	// 	"description": "Log output to console"
    	// }
    }
    ```
4. ファイルに次のスニペットコードを追加します。
    
    ```json
    {
      "Transform Message": {
        "prefix": "muledx:transform-message",
        "body": [
          "<ee:transform doc:name=\"${1:Transform Message}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\">",
          "  <ee:message>",
          "    <ee:set-payload>",
          "      <![CDATA[${2:DataWeave}]]>",
          "    </ee:set-payload>",
          "  </ee:message>",
          "</ee:transform>"
        ]
      },
      "Mule Flow": {
        "prefix": "muledx:flow",
        "body": [
          "<flow name=\"${1:$TM_FILENAME_BASE-Flow}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\">",
            "",
          "</flow>"
      ]
      },
      "HTTP Listener Config": {
        "prefix": "muledx:http-listener-config",
        "body": [
          "<http:listener-config name=\"${1:httpListenerConfig}\" doc:name=\"${2:Listener Config}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\">",
          "  <http:listener-connection host=\"${3:Host}\" port=\"${4:Port}\"/>",
          "</http:listener-config>"
        ]
      },
      "HTTP Listener": {
        "prefix": "muledx:http-listener",
        "body": [
          "<http:listener path=\"/${1:path}\" config-ref=\"${2:httpListenerConfig}\" doc:name=\"${3:Listener}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\"/>"
        ]
      },
      "Set Payload": {
        "prefix": "muledx:set-payload",
        "body": [
          "<set-payload value=\"${1:#[payload]}\" doc:name=\"${2:Set Payload}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\"/>"
        ]
      },
      "Set Variable": {
        "prefix": "muledx:set-variable",
        "body": [
          "<set-variable variableName=\"${1:name}\" value=\"${2:#[payload]}\" doc:name=\"${3:Set Variable}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\"/>"
        ]
      },
      "Logger": {
        "prefix": "muledx:logger",
        "body": [
          "<logger level=\"INFO\" message=\"${1:#[payload]}\" doc:name=\"${2:Logger}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\"/>"
        ]
      },
      "Database Config - MySQL": {
        "prefix": "muledx:db-config-mysql",
        "body": [
          "<db:config name=\"${1:DatabaseConfig}\" doc:name=\"${2:mySQL DB}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\">",
          "  <db:my-sql-connection host=\"${3:Host}\" port=\"${4:Port}\" user=\"${5:Username}\" password=\"${6:Password}\" database=\"${7:DatabaseName}\" />",
          "</db:config>"
        ]
      },
      "Database Select": {
        "prefix": "muledx:db-select",
        "body": [
          "<db:select config-ref=\"${1:DatabaseConfigRef}\" doc:name=\"${2:Select}\" doc:id=\"$RANDOM_HEX-$RANDOM_HEX\">",
          "  <db:sql>",
          "    <![CDATA[${3:SQL}]]>",
          "  </db:sql>",
          "</db:select>"
        ]
      }
    }
    ```
    
    このスニペットでは、Transform Message を含めいくつかの Mule コンポーネントの開始設定が提供されます。
5. [ペイロードを JSON として返す](#return-payload)​に進みます。

## [](#return-payload)ペイロードを JSON として返す

1. Anypoint Code Builder で ​`american-ws-anypoint-code-builder.xml`​ を開きます。
2. キャンバスで、​**Database Select**​ 操作の下にスニペット ​`[Transform Message (メッセージを変換)]`​ を挿入します。
    
    リスナーの後で ​![](/mulesoft/current/ja-jp/anypoint-code-builder/_images/icon-plus.png)​ (​**\[Add component (コンポーネントを追加)\]**​) アイコンをクリックして、​**\[Snippets (スニペット)\]**​ > ​**\[User Snippets (ユーザースニペット)\]**​ > ​**\[Transform Message (メッセージを変換)\]**​ に移動します。
    
    最初に ​**\[User Snippets (ユーザースニペット)\]**​ パネルが空になっている場合、しばらく待ってからもう一度試します。または、設定 XML から ​`muledx:transform-message`​ スニペットに移動します。
    
    ![強調表示されている Transform コンポーネント](/mulesoft/current/ja-jp/anypoint-code-builder/_images/transform-with-output-json.png)
    
    ユーザースニペット XML:
    
    ```xml
    <ee:transform doc:name="" doc:id="51fed3-afee8c">
      <ee:message>
        <ee:set-payload>
          <![CDATA[]]>
        </ee:set-payload>
      </ee:message>
    </ee:transform>
    ```
3. 設定 XML で ​`doc:name`​ の値 ​**\[Transform Message\]**​ (メッセージを変換) または同様の値を ​`<ee:transform/>`​ コンポーネントに追加します。
    
    <ee:transform doc:name="Transform Message" doc:id="423214-fac9c4">
    ...
4. `<![CDATA[]]>`​ 内で、メッセージペイロードを JSON 形式に出力する DataWeave スクリプトを追加します。
    
    ```dataweave
    <ee:transform doc:name="Transform Message" doc:id="51fed3-afee8c">
      <ee:message>
        <ee:set-payload>
          <![CDATA[
          %dw 2.0
          output application/json
          ---
          payload
          ]]>
        </ee:set-payload>
      </ee:message>
    </ee:transform>
    ```
5. **\[Run (実行)\]**​ > ​**\[Start Debugging F5 (デバッグを開始 F5)\]**​ を選択して、アプリケーションを IDE 内にデプロイします。
    
    詳細は、​[「デバッグモードでアプリケーションを実行する」](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-am-flights#run)​を参照してください。
6. アプリケーションが正常にデプロイされたら、REST クライアントまたはブラウザーを使用して応答をトリガーします。
    
    詳細は、​[「アプリケーションのテスト」](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-am-flights#test)​を参照してください。
7. MySQL データベースからの応答データを参照します。次に例を示します。
    
    ```JSON
    [
      {
        "planeType": "Boeing 787",
        "code2": "0001",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "rree",
        "fromAirport": "MUA",
        "price": 541,
        "seatsAvailable": 0,
        "toAirport": "LAX",
        "ID": 1,
        "airlineName": "American Airlines",
        "totalSeats": 200
      },
        ...
    ]
    ```
    
    完全な応答を表示するには、クリックしてください。
    
    ```json
    [
      {
        "planeType": "Boeing 787",
        "code2": "0001",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "rree",
        "fromAirport": "MUA",
        "price": 541,
        "seatsAvailable": 0,
        "toAirport": "LAX",
        "ID": 1,
        "airlineName": "American Airlines",
        "totalSeats": 200
      },
      {
        "planeType": "Boeing 747",
        "code2": "0123",
        "takeOffDate": "2016-01-25T00:00:00",
        "code1": "eefd",
        "fromAirport": "MUA",
        "price": 300,
        "seatsAvailable": 7,
        "toAirport": "CLE",
        "ID": 2,
        "airlineName": "American Airlines",
        "totalSeats": 345
      },
      {
        "planeType": "Boeing 777",
        "code2": "0192",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "ffee",
        "fromAirport": "MUA",
        "price": 300,
        "seatsAvailable": 0,
        "toAirport": "LAX",
        "ID": 3,
        "airlineName": "American Airlines",
        "totalSeats": 300
      },
      {
        "planeType": "Boeing 737",
        "code2": "1000",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "rree",
        "fromAirport": "MUA",
        "price": 200,
        "seatsAvailable": 5,
        "toAirport": "CLE",
        "ID": 4,
        "airlineName": "American Airlines",
        "totalSeats": 150
      },
      {
        "planeType": "Boeing 737",
        "code2": "1093",
        "takeOffDate": "2016-02-11T00:00:00",
        "code1": "rree",
        "fromAirport": "MUA",
        "price": 142,
        "seatsAvailable": 1,
        "toAirport": "SFO",
        "ID": 5,
        "airlineName": "American Airlines",
        "totalSeats": 150
      },
      {
        "planeType": "Boeing 787",
        "code2": "1112",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "ffee",
        "fromAirport": "MUA",
        "price": 954,
        "seatsAvailable": 100,
        "toAirport": "CLE",
        "ID": 6,
        "airlineName": "American Airlines",
        "totalSeats": 200
      },
      {
        "planeType": "Boeing 777",
        "code2": "1994",
        "takeOffDate": "2016-01-01T00:00:00",
        "code1": "eefd",
        "fromAirport": "MUA",
        "price": 676,
        "seatsAvailable": 0,
        "toAirport": "SFO",
        "ID": 7,
        "airlineName": "American Airlines",
        "totalSeats": 300
      },
      {
        "planeType": "Boeing 737",
        "code2": "2000",
        "takeOffDate": "2016-02-20T00:00:00",
        "code1": "ffee",
        "fromAirport": "MUA",
        "price": 300,
        "seatsAvailable": 30,
        "toAirport": "SFO",
        "ID": 8,
        "airlineName": "American Airlines",
        "totalSeats": 150
      },
      {
        "planeType": "Boeing 737",
        "code2": "3000",
        "takeOffDate": "2016-02-01T00:00:00",
        "code1": "eefd",
        "fromAirport": "MUA",
        "price": 900,
        "seatsAvailable": 0,
        "toAirport": "SFO",
        "ID": 9,
        "airlineName": "American Airlines",
        "totalSeats": 150
      },
      {
        "planeType": "Boeing 777",
        "code2": "4511",
        "takeOffDate": "2016-01-15T00:00:00",
        "code1": "eefd",
        "fromAirport": "MUA",
        "price": 900,
        "seatsAvailable": 100,
        "toAirport": "LAX",
        "ID": 10,
        "airlineName": "American Airlines",
        "totalSeats": 300
      },
      {
        "planeType": "Boeing 737",
        "code2": "4567",
        "takeOffDate": "2016-01-20T00:00:00",
        "code1": "rree",
        "fromAirport": "MUA",
        "price": 456,
        "seatsAvailable": 100,
        "toAirport": "SFO",
        "ID": 11,
        "airlineName": "American Airlines",
        "totalSeats": 150
      }
    ]
    ```
    
    MySQL テストサーバーを使用できない場合、このエラーが発生します。
    
    Cannot get connection for URL jdbc:mysql://mudb.learn.mulesoft.com:3306/ :
    Communications link failure.
    
    問題に対処するには、正常な応答を取得するまで再試行します。
8. [応答データの変換](#restructure)​に進みます。

## [](#restructure)応答データの変換

JSON 出力を API 仕様で必要とされる構造に変換します。

Anypoint Exchange の ​**American Flights API**​ のフライトデータで使用する構造は、データベースへの要求で返される構造とは異なります。

必要な JSON 構造を見つけるは、​`/flights`​ エンドポイントへの GET メソッドの下で JSON の例を検索します。詳細は、​[「Exchange で API を見つける」](#publish-api-spec-to-exchange.adoc#locate-your-api-in-exchange)​を参照するか、 [Exchange で API の公開バージョン](https://anypoint.mulesoft.com/exchange/68ef9520-24e9-4cf2-b2f5-620025690913/training-american-flights-api/minor/2.0/console/method/%2373/)​を開いてください。

<table class="tableblock frame-all grid-all stretch">
<colgroup>
<col style="width: 50%;">
<col style="width: 50%;">
</colgroup>
<thead>
<tr>
<th class="tableblock halign-left valign-top">API 仕様の応答の構造</th>
<th class="tableblock halign-left valign-top">実際の応答の構造</th>
</tr>
</thead>
<tbody>
<tr>
<td class="tableblock halign-left valign-top"><div class="content"><div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">[
  {
     "code": "ER38sd",
     "price": 400,
     "departureDate": "2017/07/26",
     "origin": "CLE",
     "destination": "SFO",
     "emptySeats": 0,
     "plane": {
       "type": "Boeing 737",
       "totalSeats": 150
     }
  }
]</code></pre>
</div>
</div></div></td>
<td class="tableblock halign-left valign-top"><div class="content"><div class="listingblock">
<div class="content">
<pre class="highlightjs highlight"><code class="language-json hljs" data-lang="json">[
  {
    "planeType": "Boeing 787",
    "code2": "0001",
    "takeOffDate": "2016-01-20T00:00:00",
    "code1": "rree",
    "fromAirport": "MUA",
    "price": 541,
    "seatsAvailable": 0,
    "toAirport": "LAX",
    "ID": 1,
    "airlineName": "American Airlines",
    "totalSeats": 200
  }
]</code></pre>
</div>
</div></div></td>
</tr>
</tbody>
</table>

DataWeave を使用して応答を変換します。

1. 設定 XML で ​`<![CDATA]]>`​ 内のスクリプトを DataWeave マッピングに置き換えます。
    
    ```xml
    <ee:transform doc:name="Transform Message" doc:id="51fed3-afee8c">
      <ee:message>
        <ee:set-payload>
          <![CDATA[
          %dw 2.0
          output application/json
          ---
          payload map ( payload01 , indexOfPayload01 ) -> {
            ID: payload01.ID,
            code: (payload01.code1 default "") ++ (payload01.code2 default ""),
            price: payload01.price default 0,
            departureDate: payload01.takeOffDate as String default "",
            origin: payload01.fromAirport default "",
            destination: payload01.toAirport default "",
            emptySeats: payload01.seatsAvailable default 0,
            plane: {
              "type": payload01.planeType default "",
              totalSeats: payload01.totalSeats default 0
            }
          }
          ]]>
        </ee:set-payload>
      </ee:message>
    </ee:transform>
    ```
2. 設定 XML を確認します。
    
    ```xml
    <http:listener-config name="inbound-request" doc:name="HTTP Config">
        <http:listener-connection host="0.0.0.0" port="8081" />
    </http:listener-config>
    
    <db:config name="Database_Config" doc:name="mySQL DB">
        <db:my-sql-connection host="mudb.learn.mulesoft.com" port="3306"
            user="mule" password="mule" database="training" />
    </db:config>
    
    <flow name="getFlights">
        <http:listener path="flights" config-ref="inbound-request" doc:name="HTTP /flights" />
        <db:select doc:name="Query Flights" config-ref="Database_Config" >
            <db:sql>
                <![CDATA[Select * FROM american]]>
            </db:sql>
        </db:select>
    
        <ee:transform doc:name="Transform Message">
            <ee:message >
                <ee:set-payload >
                <![CDATA[
                %dw 2.0
                output application/json
                ---
                payload map ( payload01 , indexOfPayload01 ) -> {
                  ID: payload01.ID,
                  code: (payload01.code1 default "") ++ (payload01.code2 default ""),
                  price: payload01.price default 0,
                  departureDate: payload01.takeOffDate as String default "",
                  origin: payload01.fromAirport default "",
                  destination: payload01.toAirport default "",
                  emptySeats: payload01.seatsAvailable default 0,
                  plane: {
                    "type": payload01.planeType default "",
                    totalSeats: payload01.totalSeats default 0
                  }
                }
                ]]>
                </ee:set-payload>
            </ee:message>
        </ee:transform>
    </flow>
    ```
3. [アプリケーションを実行してテストする](#run-test)​に進みます。

## [](#run-test)アプリケーションを実行してテストする

1. **\[Run (実行)\]**​ > ​**\[Start Debugging F5 (デバッグを開始 F5)\]**​ を実行して、アプリケーションを IDE 内にデプロイします。
    
    詳細は、​[「デバッグモードでアプリケーションを実行する」](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-am-flights#run)​を参照してください。
2. アプリケーションが正常にデプロイされたら、REST クライアントまたはブラウザーを使用してフローをトリガーします。
    
    詳細は、​[「アプリケーションのテスト」](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-am-flights#test)​を参照してください。
    
    変換されたデータ構造が API 要件に準拠していることを確認します。次に例を示します。
    
    ```JSON
    [
        {
            "ID": 1,
            "code": "rree0001",
            "price": 541,
            "departureDate": "2016-01-20T00:00:00",
            "origin": "MUA",
            "destination": "LAX",
            "emptySeats": 0,
            "plane": {
                "type": "Boeing 787",
                "totalSeats": 200
            }
        },
        ...
    ```
    
    完全な応答を表示するには、クリックしてください。
    
    ```JSON
    [
        {
            "ID": 1,
            "code": "rree0001",
            "price": 541,
            "departureDate": "2016-01-20T00:00:00",
            "origin": "MUA",
            "destination": "LAX",
            "emptySeats": 0,
            "plane": {
                "type": "Boeing 787",
                "totalSeats": 200
            }
        },
        {
            "ID": 2,
            "code": "eefd0123",
            "price": 300,
            "departureDate": "2016-01-25T00:00:00",
            "origin": "MUA",
            "destination": "CLE",
            "emptySeats": 7,
            "plane": {
                "type": "Boeing 747",
                "totalSeats": 345
            }
        },
        {
            "ID": 3,
            "code": "ffee0192",
            "price": 300,
            "departureDate": "2016-01-20T00:00:00",
            "origin": "MUA",
            "destination": "LAX",
            "emptySeats": 0,
            "plane": {
                "type": "Boeing 777",
                "totalSeats": 300
            }
        },
        {
            "ID": 4,
            "code": "rree1000",
            "price": 200,
            "departureDate": "2016-01-20T00:00:00",
            "origin": "MUA",
            "destination": "CLE",
            "emptySeats": 5,
            "plane": {
                "type": "Boeing 737",
                "totalSeats": 150
            }
        },
        {
            "ID": 5,
            "code": "rree1093",
            "price": 142,
            "departureDate": "2016-02-11T00:00:00",
            "origin": "MUA",
            "destination": "SFO",
            "emptySeats": 1,
            "plane": {
                "type": "Boeing 737",
                "totalSeats": 150
            }
        },
        {
            "ID": 6,
            "code": "ffee1112",
            "price": 954,
            "departureDate": "2016-01-20T00:00:00",
            "origin": "MUA",
            "destination": "CLE",
            "emptySeats": 100,
            "plane": {
                "type": "Boeing 787",
                "totalSeats": 200
            }
        },
        {
            "ID": 7,
            "code": "eefd1994",
            "price": 676,
            "departureDate": "2016-01-01T00:00:00",
            "origin": "MUA",
            "destination": "SFO",
            "emptySeats": 0,
            "plane": {
                "type": "Boeing 777",
                "totalSeats": 300
            }
        },
        {
            "ID": 8,
            "code": "ffee2000",
            "price": 300,
            "departureDate": "2016-02-20T00:00:00",
            "origin": "MUA",
            "destination": "SFO",
            "emptySeats": 30,
            "plane": {
                "type": "Boeing 737",
                "totalSeats": 150
            }
        },
        {
            "ID": 9,
            "code": "eefd3000",
            "price": 900,
            "departureDate": "2016-02-01T00:00:00",
            "origin": "MUA",
            "destination": "SFO",
            "emptySeats": 0,
            "plane": {
                "type": "Boeing 737",
                "totalSeats": 150
            }
        },
        {
            "ID": 10,
            "code": "eefd4511",
            "price": 900,
            "departureDate": "2016-01-15T00:00:00",
            "origin": "MUA",
            "destination": "LAX",
            "emptySeats": 100,
            "plane": {
                "type": "Boeing 777",
                "totalSeats": 300
            }
        },
        {
            "ID": 11,
            "code": "rree4567",
            "price": 456,
            "departureDate": "2016-01-20T00:00:00",
            "origin": "MUA",
            "destination": "SFO",
            "emptySeats": 100,
            "plane": {
                "type": "Boeing 737",
                "totalSeats": 150
            }
        }
    ]
    ```
3. アプリケーションを停止します。
    
    詳細は、​[「アプリケーションを停止する」](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-integrate-am-flights#stop)​を参照してください。
4. [American Flights API 仕様の実装](https://docs.mulesoft.com/jp/anypoint-code-builder/tut-af-implement-am-flights-api)に進みます。