Free MuleSoft CONNECT Keynote & Expo Pass Available!

Register now+
Nav

About Type Coercion with DataWeave

In DataWeave, types can be coerced from one type to other using the as operator. Type coercion takes place runtime.

Note that when you provide an operator with properties that do not match the expected types, DataWeave automatically attempts to coerce the provided property to the required type.

Defining DataWeave Types For Type Coercion

The DataWeave example defines the type Currency using the String type, formats the value with the Java DecimalFormat pattern (##), and then uses as to coerce the price values to the Currency type.

Input

         
      
1
2
3
4
5
6
7
8
<items>
    <item>
        <price>22.30</price>
    </item>
    <item>
        <price>20.31</price>
    </item>
</items>
DataWeave

         
      
1
2
3
4
5
6
7
%dw 2.0
output application/json
type Currency = String { format: "\$#,###.00"}
---
books: payload.items.*item map
    book:
        price: $.price as Currency
Output

         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
14
{
  "books": [
    {
      "book": {
        "price": "22.44"
      }
    },
    {
      "book": {
        "price": "20.31"
      }
    }
  ]
}

Type Coercion Table

This table shows the possible combinations and the properties from the schema that are used in the transformation.

Source Target Property

Range

Array

Number

Binary

String

Binary

String

Boolean

Number

DateTime

unit

LocalDateTime

DateTime

String

DateTime

format / locale

DateTime

LocalDate

LocalDateTime

LocalDate

String

LocalDate

format / locale

DateTime

LocalDateTime

String

LocalDateTime

format / locale

DateTime

LocalTime

LocalDateTime

LocalTime

Time

LocalTime

String

LocalTime

format / locale

DateTime

Number

unit

String

Number

format / locale

String

Period

String

Regex

DateTime

String

format / locale

LocalDateTime

String

format / locale

LocalTime

String

format / locale

LocalDate

String

format / locale

Time

String

format / locale

Period

String

TimeZone

String

Number

String

format / locale

Boolean

String

Range

String

Returns a string with all the values of the range using , as the separator

Type

String

DateTime

Time

LocalDateTime

Time

LocalTime

Time

String

Time

format

DateTime

TimeZone

Time

TimeZone`

String

TimeZone

Properties for Type Coercion

Property Description class

Accepts Java classes for Object types.

format

Accepts Java DecimalFormat patterns to format numbers and dates.

locale

Accepts Java locales. A Java Locale object represents a region (geographical, political, or cultural).

unit