Data conversion

How to convert data to commonly used formats.

Key takeaways

Convert Library in the Commons module that contains data conversion components.
ArrayConverter Provides methods to create an array from a set of values.
BooleanConverter Provides methods to convert a value into a Boolean.
DateTimeConverter Provides methods to convert a value into a Date.
DoubleConverter Provides methods to convert a value into a double.
FloatConverter Provides methods to convert a value into a float.
IntegerConverter Provides methods to convert a value into an integer.
LongConverter Provides methods to convert a value into a long.
StringConverter Provides methods to convert a value into a string.
JsonConverter Provides methods to convert a value from/into a JSON string.
MapConverter Provides methods to convert a value into a map.
RecursiveMapConverter Provides methods to convert a value into a map in a recursive manner.
TypeConverter Provides methods to convert a value into an object specified by a type code and to get the type code of an object.

Introduction

This tutorial will help you to understand the different conversion components available in the Pip.Services toolkit, Commons module, convert library. The tutorial consists of a brief explanation of each class and its methods followed by a set of examples that show how to use each of them.

Convertors

This section contains a brief description of each class and its methods.

1) ArrayConverter

This class provides methods to create an array from a set of values. Its methods are summarized in the table and examples below.

Method Description
to_array Converts a value into an array object with an empty array as default. Single values are converted into arrays with a single element.
to_array_with_default Converts a value into an array object with a specified default. Single values are converted into arrays with a single element.
list_to_array Converts a list into an array object, with an empty array as default. Strings with comma-delimited values are split into an array of strings.
to_nullable_array Converts a value into an array object. Single values are converted into arrays with a single element.
// Array converter

import { ArrayConverter } from "pip-services3-commons-nodex";

let value1 = ArrayConverter.toArray([1, 2]);                // Returns [1, 2]
let value2 = ArrayConverter.toArray(1);                     // Returns [1]
let value3 = ArrayConverter.toArrayWithDefault(null, [1]);  // Returns [1]
let value4 = ArrayConverter.listToArray("1,2,3");           // Returns ['1', '2', '3']
let value5 = ArrayConverter.toNullableArray("1,2");         // Returns ['1,2']

// Array converter

using PipServices3.Commons.Convert;

var value1 = ArrayConverter.ToArray(new List<int>() { 1, 2 });                  // Returns [1, 2]
var value2 = ArrayConverter.ToArray(1);                                         // Returns [1]
var value3 = ArrayConverter.ToArrayWithDefault(null, new List<object>() { 1 }); // Returns [1]
var value4 = ArrayConverter.ListToArray("1,2,3");                               // Returns ['1', '2', '3']
var value5 = ArrayConverter.ToNullableArray("1,2");                             // Returns ['1,2']

// Array converter

import (
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)
value1 := convert.ArrayConverter.ToArray([]int{1, 2}) // Returns [1, 2]
value2 := convert.ArrayConverter.ToArray(1)           // Returns [1]

defaultValue := make([]interface{}, 0)
defaultValue = append(defaultValue, 1)

value3 := convert.ArrayConverter.ToArrayWithDefault(nil, defaultValue) // Returns [1]
value4 := convert.ArrayConverter.ListToArray("1,2,3")                  // Returns ['1', '2', '3']
value5 := convert.ArrayConverter.ToNullableArray("1,2")                // Returns ['1,2']

// Array converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = ArrayConverter.toArray([1, 2]);                // Returns [1, 2]
var value2 = ArrayConverter.toArray(1);                     // Returns [1]
var value3 = ArrayConverter.toArrayWithDefault(null, [1]);  // Returns [1]
var value4 = ArrayConverter.listToArray('1,2,3');           // Returns ['1', '2', '3']
var value5 = ArrayConverter.toNullableArray('1,2');         // Returns ['1,2']

# Array converter

from pip_services3_commons.convert import ArrayConverter

value1 = ArrayConverter.to_array([1, 2])       # Returns [1, 2]
value2 = ArrayConverter.to_array(1)            # Returns [1]
value3 = ArrayConverter.to_array_with_default(None,[1])      # Returns [1]
value4 = ArrayConverter.list_to_array("1,2,3")               # Returns ['1', '2', '3']
value5 = ArrayConverter.to_nullable_array('1,2')             # Returns ['1,2']
Not available

2) BooleanConverter

This class can be used to convert different values to Boolean values using extended conversion rules. The rules and methods provided by this class are summarized in the tables and examples below.

Conversion rules
Number <>0 are true, =0 are false.
String "true", "yes", "T", "Y", "1" are true; "false", "no", "F", "N" are false.
DateTime <>0 total milliseconds are true, =0 are false.
Method Description
to_boolean Converts a value into a boolean or returns false when the conversion is not possible.
to_boolean_with_default Converts a value into a boolean or returns a default value when the conversion is not possible.
to_nullable_boolean Converts value into a boolean or returns None when the conversion is not possible.
// Boolean converter

import { BooleanConverter } from "pip-services3-commons-nodex";

let value1 = BooleanConverter.toBoolean("yes");                     // Returns True
let value2 = BooleanConverter.toBooleanWithDefault(true, false);    // Returns True
let value3 = BooleanConverter.toBooleanWithDefault(123, false);     // Returns True
let value4 = BooleanConverter.toNullableBoolean(true);              // Returns True
let value5 = BooleanConverter.toNullableBoolean("yes");             // Returns True
let value6 = BooleanConverter.toNullableBoolean(123);               // Returns True
let value7 = BooleanConverter.toNullableBoolean({});                // Returns null

// Boolean converter

using PipServices3.Commons.Convert;

var value1 = BooleanConverter.ToBoolean("yes");                 // Returns True
var value2 = BooleanConverter.ToBooleanWithDefault(true, false);// Returns True   
var value3 = BooleanConverter.ToBooleanWithDefault(123, false); // Returns False
var value4 = BooleanConverter.ToNullableBoolean(true);          // Returns True
var value5 = BooleanConverter.ToNullableBoolean("yes");         // Returns True
var value6 = BooleanConverter.ToNullableBoolean(123);           // Returns null
var value7 = BooleanConverter.ToNullableBoolean(new object());  // Returns null

// Boolean converter

import (
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.BooleanConverter.ToBoolean("yes")                          // Returns True
value2 := convert.BooleanConverter.ToBooleanWithDefault(true, false)         // Returns True
value3 := convert.BooleanConverter.ToBooleanWithDefault(123, false)          // Returns False
value4 := *convert.BooleanConverter.ToNullableBoolean(true)                  // Returns True
value5 := *convert.BooleanConverter.ToNullableBoolean("yes")                 // Returns True
value6 := convert.BooleanConverter.ToNullableBoolean(123)                    // Returns nil
value7 := convert.BooleanConverter.ToNullableBoolean(make([]interface{}, 0)) // Returns nil

// Boolean converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = BooleanConverter.toBoolean('yes');                 // Returns True
var value2 = BooleanConverter.toBooleanWithDefault(true, false);// Returns True
var value3 = BooleanConverter.toBooleanWithDefault(123, false); // Returns True
var value4 = BooleanConverter.toNullableBoolean(true);          // Returns True
var value5 = BooleanConverter.toNullableBoolean('yes');         // Returns True
var value6 = BooleanConverter.toNullableBoolean(123);           // Returns True
var value7 = BooleanConverter.toNullableBoolean({});            // Returns null

# Boolean converter

from pip_services3_commons.convert import BooleanConverter

value1 = BooleanConverter.to_boolean("yes")            # Returns True
value2 = BooleanConverter.to_boolean_with_default(True, False)     # Returns True   
value3 = BooleanConverter.to_boolean_with_default(123, False)      # Returns False
value4 = BooleanConverter.to_nullable_boolean(True)    # Returns True
value5 = BooleanConverter.to_nullable_boolean("yes")   # Returns True
value6 = BooleanConverter.to_nullable_boolean(123)     # Returns None
value7 = BooleanConverter.to_nullable_boolean({})      # Returns None

Not available

3) DateTimeConverter

This class can be used to convert arbitrary values into Date values using extended conversion rules. Its methods and conversion rules are explained in the tables and examples below.

Conversion rules
String Converts using the ISO time format.
Number Converts using milliseconds since Unix epoch.
Method Description
to_datetime Converts a value into Date or returns the current date when the conversion is not possible.
to_date_time_with_default Converts a value into Date or returns a default date when the conversion is not possible.
to_nullable_date_time Converts a value into Date or returns None when the conversion is not possible.
// Date time converter

import { DateTimeConverter } from "pip-services3-commons-nodex";

let value0 = DateTimeConverter.toDateTime("2021-11-09T17:24:50.750Z");          // Returns 2021-11-09 17:24:50.75
let value1 = DateTimeConverter.toNullableDateTime("ABC");                       // Returns null
let value2 = DateTimeConverter.toNullableDateTime("2021-11-09T17:24:50.750Z");  // Returns 2021-11-09 17:24:50.75
let value3 = DateTimeConverter.toNullableDateTime(12345657755000);              // Returns 2361-03-21 16:22:35
let value4 = DateTimeConverter.toDateTimeWithDefault("ABC", new Date());        // Returns current datetime
let value5 = DateTimeConverter.toDateTimeWithDefault("2021-11-09T17:24:50.750Z", new Date()); // Returns 2021-11-09 17:24:50.75

// Date time converter

using PipServices3.Commons.Convert;

var value0 = DateTimeConverter.ToDateTime("2021-11-09T17:24:50.750Z");  // Returns 2021-11-09 17:24:50.75
var value1 = DateTimeConverter.ToNullableDateTime("ABC");               // Returns null
var value2 = DateTimeConverter.ToNullableDateTime("2021-11-09T17:24:50.750Z"); // Returns 2021-11-09 17:24:50.75
var value3 = DateTimeConverter.ToNullableDateTime(1234565775500);   // Returns 0001-01-02 10:17:36
var value4 = DateTimeConverter.ToDateTimeWithDefault("ABC", DateTime.Now);  // Returns current datetime
var value5 = DateTimeConverter.ToDateTimeWithDefault("2021-11-09T17:24:50.750Z", DateTime.Now); // Returns 2021-11-09 17:24:50.75

// Date time converter

// Returns 2021-11-09 17:24:50.75
value0 := convert.DateTimeConverter.ToDateTime("2021-11-09T17:24:50.750Z")   

// Returns nil                  
value1 := convert.DateTimeConverter.ToNullableDateTime("ABC")     

// Returns 2021-11-09 17:24:50.75                        
value2 := convert.DateTimeConverter.ToNullableDateTime("2021-11-09T17:24:50.750Z")

// Returns 2361-03-21 16:22:35                
value3 := convert.DateTimeConverter.ToNullableDateTime(12345657755000)  

// Returns current datetime                   
value4 := convert.DateTimeConverter.ToDateTimeWithDefault("ABC", time.Now())    

// Returns 2021-11-09 17:24:50.75    
value5 := convert.DateTimeConverter.ToDateTimeWithDefault("2021-11-09T17:24:50.750Z", time.Now()) 
// Date time converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value0 = DateTimeConverter.toDateTime('2021-11-09T17:24:50.750Z');          // Returns 2021-11-09 17:24:50.75
var value1 = DateTimeConverter.toNullableDateTime('ABC');                       // Returns null
var value2 = DateTimeConverter.toNullableDateTime('2021-11-09T17:24:50.750Z');  // Returns 2021-11-09 17:24:50.75
var value3 = DateTimeConverter.toNullableDateTime(12345657755000);              // Returns 2361-03-21 16:22:35
var value4 = DateTimeConverter.toDateTimeWithDefault('ABC', DateTime.now());    // Returns current datetime
var value5 = DateTimeConverter.toDateTimeWithDefault('2021-11-09T17:24:50.750Z', DateTime.now()); // Returns 2021-11-09 17:24:50.75

# Date time converter

from pip_services3_commons.convert import DateTimeConverter
from datetime import date

value0 = DateTimeConverter.to_datetime("2021-11-09T17:24:50.750Z")              # Returns 2021-11-09 17:24:50.75
value1 = DateTimeConverter.to_nullable_datetime("ABC")                          # Returns None
value2 = DateTimeConverter.to_nullable_datetime("2021-11-09T17:24:50.750Z")     # Returns 2021-11-09 17:24:50.75
value3 = DateTimeConverter.to_nullable_datetime(12345657755000)                 # Returns 2361-03-21 16:22:35
value4 = DateTimeConverter.to_datetime_with_default("ABC", date.today())        # Returns current datetime
value4 = DateTimeConverter.to_datetime_with_default("2021-11-09T17:24:50.750Z", date.today())   # Returns 2021-11-09 17:24:50.75
Not available

4) DoubleConverter

This class is used to convert arbitrary values into doubles using extended conversion rules. The rules and available methods are explained in the following tables and examples.

Conversion rules
String Converts to a double value.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_double Converts a value into a double or returns 0 when the conversion is not possible.
to_double_with_default Converts a value into a double or returns a default value when the conversion is not possible.
to_nullable_double Converts a value into a double or returns None when the conversion is not possible.
// Double converter

import { DoubleConverter } from "pip-services3-commons-nodex";

let value1 = DoubleConverter.toDouble("123.456");               // Returns 123.456
let value2 = DoubleConverter.toDouble("ABC");                   // Returns 0
let value3 = DoubleConverter.toDoubleWithDefault("123.456", 0); // Returns 123.456
let value4 = DoubleConverter.toDoubleWithDefault("ABC", 0);     // Returns 0
let value5 = DoubleConverter.toNullableDouble("123.456");       // Returns 123.456
let value6 = DoubleConverter.toNullableDouble("ABC");           // Returns null
let value7 = DoubleConverter.toNullableDouble(true);            // Returns 1

// Double converter

using PipServices3.Commons.Convert;

var value1 = DoubleConverter.ToDouble("123.456");               // Returns 123.456
var value2 = DoubleConverter.ToDouble("ABC");                   // Returns 0
var value3 = DoubleConverter.ToDoubleWithDefault("123.456", 0); // Returns 123.456
var value4 = DoubleConverter.ToDoubleWithDefault("ABC", 0);     // Returns 0
var value5 = DoubleConverter.ToNullableDouble("123.456");       // Returns 123.456
var value6 = DoubleConverter.ToNullableDouble("ABC");           // Returns null
var value7 = DoubleConverter.ToNullableDouble(true);            // Returns 1

// Double converter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.DoubleConverter.ToDouble("123.456")               // Returns 123.456
value2 := convert.DoubleConverter.ToDouble("ABC")                   // Returns 0
value3 := convert.DoubleConverter.ToDoubleWithDefault("123.456", 0) // Returns 123.456
value4 := convert.DoubleConverter.ToDoubleWithDefault("ABC", 0)     // Returns 0
value5 := convert.DoubleConverter.ToNullableDouble("123.456") // Returns 123.456
value6 := convert.DoubleConverter.ToNullableDouble("ABC")     // Returns nil
value7 := convert.DoubleConverter.ToNullableDouble(true)      // Returns 1
// Double converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = DoubleConverter.toDouble('123.456');               // Returns 123.456
var value2 = DoubleConverter.toDouble('ABC');                   // Returns 0
var value3 = DoubleConverter.toDoubleWithDefault('123.456', 0); // Returns 123.456
var value4 = DoubleConverter.toDoubleWithDefault('ABC', 0);     // Returns 0
var value5 = DoubleConverter.toNullableDouble('123.456');       // Returns 123.456
var value6 = DoubleConverter.toNullableDouble('ABC');           // Returns null
var value7 = DoubleConverter.toNullableDouble(true);            // Returns 1

# Double converter

from pip_services3_commons.convert import DoubleConverter

value1 = DoubleConverter.to_double("123.456")                   # Returns 123.456
value2 = DoubleConverter.to_double("ABC")                       # Returns 0
value3 = DoubleConverter.to_double_with_default("123.456", 0)   # Returns 123.456
value4 = DoubleConverter.to_double_with_default("ABC", 0)       # Returns 0
value5 = DoubleConverter.to_nullable_double("123.456")       # Returns 123.456
value6 = DoubleConverter.to_nullable_double("ABC")           # Returns None
value7 = DoubleConverter.to_nullable_double(True)            # Returns 1
Not available

5) FloatConverter

This class can be used to convert arbitrary values into floats using extended conversion rules. Its methods and conversion rules are explained in the tables and examples below.

Conversion rules
String Converts to a float value.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_float Converts a value into a float or returns 0 when the conversion is not possible.
to_float_with_default Converts a value into a float or returns a default value when the conversion is not possible.
to_nullable_float Converts a value into a float or returns None when the conversion is not possible.
// Float converter
import { FloatConverter } from "pip-services3-commons-nodex";

let value1 = FloatConverter.toFloat("123.456");                 // Returns 123.456
let value2 = FloatConverter.toFloat("ABC");                     // Returns 0
let value3 = FloatConverter.toFloatWithDefault("123.456", 0);   // Returns 123.456
let value4 = FloatConverter.toFloatWithDefault("ABC", 0);       // Returns 0
let value5 = FloatConverter.toNullableFloat("123.456");         // Returns 123.456
let value6 = FloatConverter.toNullableFloat("ABC");             // Returns null
let value7 = FloatConverter.toNullableFloat(true);              // Returns 1


// Float converter
using PipServices3.Commons.Convert;

var value1 = FloatConverter.ToFloat("123.456");                 // Returns 123.456
var value2 = FloatConverter.ToFloat("ABC");                     // Returns 0
var value3 = FloatConverter.ToFloatWithDefault("123.456", 0);   // Returns 123.456
var value4 = FloatConverter.ToFloatWithDefault("ABC", 0);       // Returns 0
var value5 = FloatConverter.ToNullableFloat("123.456");         // Returns 123.456
var value6 = FloatConverter.ToNullableFloat("ABC");             // Returns null
var value7 = FloatConverter.ToNullableFloat(true);              // Returns 1


// Float converter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.FloatConverter.ToFloat("123.456")               // Returns 123.456
value2 := convert.FloatConverter.ToFloat("ABC")                   // Returns 0
value3 := convert.FloatConverter.ToFloatWithDefault("123.456", 0) // Returns 123.456
value4 := convert.FloatConverter.ToFloatWithDefault("ABC", 0)     // Returns 0
value5 := *convert.FloatConverter.ToNullableFloat("123.456")      // Returns 123.456
value6 := convert.FloatConverter.ToNullableFloat("ABC")           // Returns nil
value7 := *convert.FloatConverter.ToNullableFloat(true)           // Returns 1

// Float converter
import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = FloatConverter.toFloat('123.456'); // Returns 123.456
var value2 = FloatConverter.toFloat('ABC'); // Returns 0
var value3 = FloatConverter.toFloatWithDefault('123.456', 0); // Returns 123.456
var value4 = FloatConverter.toFloatWithDefault('ABC', 0); // Returns 0
var value5 = FloatConverter.toNullableFloat('123.456'); // Returns 123.456
var value6 = FloatConverter.toNullableFloat('ABC'); // Returns null
var value7 = FloatConverter.toNullableFloat(true); // Returns 1


# Float converter
from pip_services3_commons.convert import FloatConverter

value1 = FloatConverter.to_float("123.456")                 # Returns 123.456
value2 = FloatConverter.to_float("ABC")                     # Returns 0
value3 = FloatConverter.to_float_with_default("123.456", 0) # Returns 123.456
value4 = FloatConverter.to_float_with_default("ABC", 0)     # Returns 0
value5 = FloatConverter.to_nullable_float("123.456")        # Returns 123.456
value6 = FloatConverter.to_nullable_float("ABC")            # Returns None
value7 = FloatConverter.to_nullable_float(True)             # Returns 1

Not available

6) IntegerConverter

This class is used to convert arbitrary values into integers using extended conversion rules. Its methods and rules are explained in the following tables and examples.

Conversion rules
String Converts to float, then to integer.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_integer Converts a value into an integer or returns 0 when the conversion is not possible.
to_integer_with_default Converts a value into an integer or returns a default value when the conversion is not possible.
to_nullable_integer Converts a value into an integer or returns None when the conversion is not possible.
// IntegerConverter
import { IntegerConverter } from "pip-services3-commons-nodex";

let value1 = IntegerConverter.toInteger("123.456");                 // Returns 123
let value2 = IntegerConverter.toInteger("ABC");                     // Returns 0
let value3 = IntegerConverter.toNullableInteger("123.456");         // Returns 123
let value4 = IntegerConverter.toNullableInteger("ABC");             // Returns null
let value5 = IntegerConverter.toNullableInteger(true);              // Returns 1
let value6 = IntegerConverter.toIntegerWithDefault("ABC", 123);     // Returns 123 
let value7 = IntegerConverter.toIntegerWithDefault("123.456", 123); // Returns 123 


// IntegerConverter
using PipServices3.Commons.Convert;

var value1 = IntegerConverter.ToInteger("123.456");                 // Returns 123
var value2 = IntegerConverter.ToInteger("ABC");                     // Returns 0
var value3 = IntegerConverter.ToNullableInteger("123.456");         // Returns 123
var value4 = IntegerConverter.ToNullableInteger("ABC");             // Returns null
var value5 = IntegerConverter.ToNullableInteger(true);              // Returns 1
var value6 = IntegerConverter.ToIntegerWithDefault("ABC", 123);     // Returns 123 
var value7 = IntegerConverter.ToIntegerWithDefault("123.456", 123); // Returns 123 


// IntegerConverter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.IntegerConverter.ToInteger("123.456")                 // Returns 123
value2 := convert.IntegerConverter.ToInteger("ABC")                     // Returns 0
value3 := *convert.IntegerConverter.ToNullableInteger("123.456")        // Returns 123
value4 := convert.IntegerConverter.ToNullableInteger("ABC")             // Returns nil
value5 := *convert.IntegerConverter.ToNullableInteger(true)             // Returns 1
value6 := convert.IntegerConverter.ToIntegerWithDefault("ABC", 123)     // Returns 123
value7 := convert.IntegerConverter.ToIntegerWithDefault("123.456", 123) // Returns 123

// IntegerConverter
import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = IntegerConverter.toInteger('123.456');                 // Returns 123
var value2 = IntegerConverter.toInteger('ABC');                     // Returns 0
var value3 = IntegerConverter.toNullableInteger('123.456');         // Returns 123
var value4 = IntegerConverter.toNullableInteger('ABC');             // Returns null
var value5 = IntegerConverter.toNullableInteger(true);              // Returns 1
var value6 = IntegerConverter.toIntegerWithDefault('ABC', 123);     // Returns 123
var value7 = IntegerConverter.toIntegerWithDefault('123.456', 123); // Returns 123


# IntegerConverter
from pip_services3_commons.convert import IntegerConverter

value1 = IntegerConverter.to_integer("123.456")                     # Returns 123
value2 = IntegerConverter.to_integer("ABC")                         # Returns 0
value3 = IntegerConverter.to_nullable_integer("123.456")            # Returns 123
value4 = IntegerConverter.to_nullable_integer("ABC")                # Returns None
value5 = IntegerConverter.to_nullable_integer(True)                 # Returns 1
value6 = IntegerConverter.to_integer_with_default("ABC", 123)       # Returns 123  
value7 = IntegerConverter.to_integer_with_default("123.456", 123)   # Returns 123  

Not available

7) LongConverter

This class is used to convert arbitrary values into longs using extended conversion rules. Its methods and rules are explained in the following tables and examples.

Conversion rules
String Converts to float, then to long.
DateTime Total number of milliseconds since Unix epoch.
Boolean 1 for true and 0 for false.
Method Description
to_long Converts a value into a long or returns 0 when the conversion is not possible.
to_long_with_default Converts a value into a long or returns a default value when the conversion is not possible.
to_nullable_long Converts a value into a long or returns None when the conversion is not possible.
// Long converter

import { LongConverter } from "pip-services3-commons-nodex";


let value1 = LongConverter.toLong("123.456");               // Returns 123
let value2 = LongConverter.toLong("ABC");                   // Returns 0
let value3 = LongConverter.toNullableLong("123.456");       // Returns 123
let value4 = LongConverter.toNullableLong("ABC");           // Returns null
let value5 = LongConverter.toNullableLong(true);            // Returns 1
let value6 = LongConverter.toLongWithDefault("123.456", 0); // Returns 123
let value7 = LongConverter.toLongWithDefault("ABC", 0);     // Returns 0

// Long converter

using PipServices3.Commons.Convert;

var value1 = LongConverter.ToLong("123.456");               // Returns 123
var value2 = LongConverter.ToLong("ABC");                   // Returns 0
var value3 = LongConverter.ToNullableLong("123.456");       // Returns 123
var value4 = LongConverter.ToNullableLong("ABC");           // Returns null
var value5 = LongConverter.ToNullableLong(true);            // Returns 1
var value6 = LongConverter.ToLongWithDefault("123.456", 0); // Returns 123
var value7 = LongConverter.ToLongWithDefault("ABC", 0);     // Returns 0

// Long converter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.LongConverter.ToLong("123.456")               // Returns 123
value2 := convert.LongConverter.ToLong("ABC")                   // Returns 0
value3 := *convert.LongConverter.ToNullableLong("123.456")      // Returns 123
value4 := convert.LongConverter.ToNullableLong("ABC")           // Returns nil
value5 := *convert.LongConverter.ToNullableLong(true)           // Returns 1
value6 := convert.LongConverter.ToLongWithDefault("123.456", 0) // Returns 123
value7 := convert.LongConverter.ToLongWithDefault("ABC", 0)     // Returns 0
// Long converter

import 'package:pip_services3_commons/pip_services3_commons.dart';


var value1 = LongConverter.toLong('123.456');                // Returns 123
var value2 = LongConverter.toLong('ABC');                    // Returns 0
var value3 = LongConverter.toNullableLong('123.456');        // Returns 123
var value4 = LongConverter.toNullableLong('ABC');            // Returns null
var value5 = LongConverter.toNullableLong(true);             // Returns 1
var value6 = LongConverter.toLongWithDefault('123.456', 0);  // Returns 123
var value7 = LongConverter.toLongWithDefault('ABC', 0);      // Returns 0

# Long converter

from pip_services3_commons.convert import LongConverter

value1 = LongConverter.to_long("123.456")                   # Returns 123
value2 = LongConverter.to_long("ABC")                       # Returns 0
value3 = LongConverter.to_nullable_long("123.456")          # Returns 123
value4 = LongConverter.to_nullable_long("ABC")              # Returns None
value5 = LongConverter.to_nullable_long(True)               # Returns 1
value6 = LongConverter.to_long_with_default("123.456", 0)   # Returns 123
value7 = LongConverter.to_long_with_default("ABC", 0)       # Returns 0
Not available

8) StringConverter

This class is used to convert arbitrary values into strings. Its methods and conversion rules are explained in the tables and examples below.

Conversion rules
Number Converts with '.' as decimal point.
DateTime Converts using the ISO format.
Boolean Converts "true" for true and "false" for false.
Array Converts as comma-separated list.
Other Converts using the to_string() method.
Method Description
to_string Converts a value into a string or returns "" when the value is None.
to_nullable_string Converts a value into a string or returns None when the value is None.
to_string_with_default Converts a value into a string or returns a default value when the value is None.
// String converter

import { StringConverter } from "pip-services3-commons-nodex";

let value1 = StringConverter.toString(123.456);                 // Returns '123.456'
let value2 = StringConverter.toString(true);                    // Returns 'True'
let value3 = StringConverter.toString(new Date(2018, 10, 1));   // Returns '2018-10-01T00:00:00Z'
let value4 = StringConverter.toString([ "a", "b", "c" ]);       // Returns 'a,b,c'
let value5 = StringConverter.toString(null);                    // Returns ""
let value6 = StringConverter.toNullableString(null);            // Returns null
let value7 = StringConverter.toStringWithDefault(null, "my default");   // Returns 'my default' 

// String converter

using PipServices3.Commons.Convert;

var value1 = StringConverter.ToString(123.456);                         // Returns '123.456'
var value2 = StringConverter.ToString(true);                            // Returns 'True'
var value3 = StringConverter.ToString(new DateTime(2018, 10, 1));       // Returns '2018-10-01T00:00:00Z'
var value4 = StringConverter.ToString(new List<string>() { "a", "b", "c" });    // Returns 'a,b,c'
var value5 = StringConverter.ToString(null);                            // Returns ""
var value6 = StringConverter.ToNullableString(null);                    // Returns null
var value7 = StringConverter.ToStringWithDefault(null, "my default");   // Returns 'my default' 

// String converter

import (
	"fmt"
	"time"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.StringConverter.ToString(123.456)                                      // Returns '123.456'
value2 := convert.StringConverter.ToString(true)                                         // Returns 'True'
value3 := convert.StringConverter.ToString(time.Date(2018, 10, 1, 0, 0, 0, 0, time.UTC)) // Returns '2018-10-01T00:00:00Z'
value4 := convert.StringConverter.ToString([]string{"a", "b", "c"})                      // Returns 'a,b,c'
value5 := convert.StringConverter.ToString(nil)                                          // Returns ""
value6 := convert.StringConverter.ToNullableString(nil)                                  // Returns nil
value7 := convert.StringConverter.ToStringWithDefault(nil, "my default")                 // Returns 'my default'
// String converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = StringConverter.toString2(123.456);                      // Returns '123.456'
var value2 = StringConverter.toString2(true);                         // Returns 'True'
var value3 = StringConverter.toString2(DateTime(2018, 10, 1));        // Returns '2018-10-01T00:00:00Z'
var value4 = StringConverter.toString2(['a', 'b', 'c']);              // Returns 'a,b,c'
var value5 = StringConverter.toString2(null);                         // Returns ""
var value6 = StringConverter.toNullableString(null);                  // Returns null
var value7 = StringConverter.toStringWithDefault(null, 'my default'); // Returns 'my default'

# String converter

from pip_services3_commons.convert import StringConverter
import datetime

value1 = StringConverter.to_string(123.456)     # Returns '123.456'
value2 = StringConverter.to_string(True)        # Returns 'True'
value3 = StringConverter.to_string(datetime.datetime(2018,10,1))       # Returns '2018-10-01T00:00:00Z'
value4 = StringConverter.to_string(["a","b","c"])     # Returns 'a,b,c'
value5 = StringConverter.to_string(None)              # Returns ""
value6 = StringConverter.to_nullable_string(None)     # Returns None
value7 = StringConverter.to_string_with_default(None,"my default")     # Returns 'my default' 
Not available

9) JsonConverter

This class is used to convert arbitrary values (e.g. a JSON object) from and to JSON (JavaScript Object Notation) strings. Its methods are explained in the table and examples below.

Method Description
from_json Converts a JSON string into a value of the type specified by a TypeCode.
to_json Converts a value into a JSON string.
to_map Converts a JSON string into a map object or returns an empty map when the conversion is not possible.
to_map_with_default Converts a JSON string into a map object or returns a default value when the conversion is not possible.
to_nullable_map Converts a JSON string into a map object or returns None when the conversion is not possible.
// JSON converter
import { JsonConverter, TypeCode } from "pip-services3-commons-nodex";

let value1 = JsonConverter.toJson({ "key": 123 });                           // Returns '{"key": 123}'
let value2 = JsonConverter.fromJson(TypeCode.Map, "{\"key\":\"123\"}");      // Returns {'key': '123'}
let value3 = JsonConverter.toMap(value1);                                    // Returns {'key': 123}
let value4 = JsonConverter.toMapWithDefault(value1, { "my key": "my val" }); // Returns {'key': 123}
let value5 = JsonConverter.toMapWithDefault("", { "my key": "my val" });     // Returns { "my key": "my val" }
let value6 = JsonConverter.toNullableMap(value1);                            // Returns {'key': 123}
let value7 = JsonConverter.toNullableMap("{}");                              // Returns {}
    

// JSON converter
using PipServices3.Commons.Convert;

var value1 = JsonConverter.ToJson(new Dictionary<string, object> { { "key", 123 } });   // Returns '{"key": 123}'
var value2 = JsonConverter.FromJson<Dictionary<string, string>>("{\"key\":\"123\"}");   // Returns {'key': '123'}
var value3 = JsonConverter.ToMap(value1);                                               // Returns {'key': 123}
var value4 = JsonConverter.ToMapWithDefault(value1, new Dictionary<string, object> { { "my key", "my val" } }); // Returns {'key': 123}
var value5 = JsonConverter.ToMapWithDefault("{}", new Dictionary<string, object> { { "my key", "my val" } });   // Returns {}
var value6 = JsonConverter.ToNullableMap(value1);   // Returns {'key': 123}
var value7 = JsonConverter.ToNullableMap("{}");     // Returns {}

// JSON converter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1, _ := convert.ToJson(map[string]int{"key": 123})                                              // Returns '{"key": 123}'
value2, _ := convert.FromJson("{\"key\":\"123\"}")                                                   // Returns {"key": 123}
value3 := convert.JsonConverter.ToMap(value1)                                                        // Returns {"key": 123}
value4 := convert.JsonConverter.ToMapWithDefault(value1, map[string]interface{}{"my key": "my val"}) // Returns {"key": 123}
value5 := convert.JsonConverter.ToMapWithDefault("", map[string]interface{}{"my key": "my val"})     // Returns {}
value6 := convert.JsonConverter.ToNullableMap(value1)                                                // Returns {'key': 123}
value7 := convert.JsonConverter.ToNullableMap("{}")                                                    // Returns {}
// JSON converter
import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = JsonConverter.toJson({'key': 123});                            // Returns '{"key": 123}'
var value2 = JsonConverter.fromJson(TypeCode.Map, '{\"key\":\"123\"}');     // Returns {'key': '123'}
var value3 = JsonConverter.toMap(value1!);                                  // Returns {'key': 123}
var value4 = JsonConverter.toMapWithDefault(value1, {'my key': 'my val'});  // Returns {'key': 123}
var value5 = JsonConverter.toMapWithDefault('', {'my key': 'my val'});      // Returns { "my key": "my val" }
var value6 = JsonConverter.toNullableMap(value1);                           // Returns {'key': 123}
var value7 = JsonConverter.toNullableMap('{}');                             // Returns {}
    

# JSON converter
from pip_services3_commons.convert import JsonConverter, TypeCode

value1 = JsonConverter.to_json({'key': 123})                                # Returns '{"key": 123}'
value2 = JsonConverter.from_json(TypeCode.Map, '{"key":"123"}')          # Returns {'key': '123'}
value3 = JsonConverter.to_map(value1)                                       # Returns {'key': 123}
value4 = JsonConverter.to_map_with_default(value1, {"my key": "my val"})    # Returns {'key': 123}
value5 = JsonConverter.to_map_with_default("", {"my key": "my val"})        # Returns {"my key": "my val"}
value6 = JsonConverter.to_nullable_map(value1)                              # Returns {'key': 123}
value7 = JsonConverter.to_nullable_map("")                                  # Returns None
Not available

10) MapConverter & RecursiveMapConverter

Both classes are used to convert arbitrary values into map objects using extended conversion rules. The difference between them is that RecursiveMapConverter uses recursion to convert all values stored in objects and arrays, and MapConverter doesn’t. The tables and examples below explain their methods and conversion rules.

Conversion rules
Objects Property names as keys, property values as values.
Arrays Element indexes as keys, elements as values.
MapConverter
Method Description
to_map Converts a value into a map object or returns an empty map when the conversion is not possible.
to_map_with_default Converts a value into a map object or returns a default value when the conversion is not possible.
to_nullable_map Converts a value into a map object or returns None when the conversion is not possible.
// Map converter

import { MapConverter } from "pip-services3-commons-nodex";

let value1 = MapConverter.toNullableMap("ABC");                       // Returns null
let value2 = MapConverter.toNullableMap({ "key": 123 });              // Returns { key: 123 }
let value3 = MapConverter.toNullableMap([1, 2, 3]);                   // Returns { "0": 1, "1": 2, "2": 3 }
let value4 = MapConverter.toMap("ABC");                               // Returns {}
let value5 = MapConverter.toMapWithDefault("ABC", value2);            // Returns {'key': 123}
let value6 = MapConverter.toMapWithDefault({ "key": 12345 }, value2); // Returns {'key': 12345}


// Map converter

using PipServices3.Commons.Convert;

var value1 = MapConverter.ToNullableMap("ABC");                                         // Returns null
var value2 = MapConverter.ToNullableMap(new Dictionary<string, object>() { { "key", 123 } });   // Returns { key: 123 }
var value3 = MapConverter.ToNullableMap(new List<int>() { 1, 2, 3 });                   // Returns { "0": 1, "1": 2, "2": 3 }
var value4 = MapConverter.ToMap("ABC");                                                 // Returns {}
var value5 = MapConverter.ToMapWithDefault("ABC", (Dictionary<string, object>)value2);  // Returns {'key': 123}
var value6 = MapConverter.ToMapWithDefault(new Dictionary<string, object>() { { "key", 12345 } }, (Dictionary<string, object>)value2); // Returns {'key': 12345}


// Map converter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.MapConverter.ToNullableMap("ABC")                                            // Returns nil
value2 := convert.MapConverter.ToNullableMap(map[string]interface{}{"key": 123})               // Returns { key: 123 }
value3 := convert.MapConverter.ToNullableMap([]int{1, 2, 3})                                   // Returns { "0": 1, "1": 2, "2": 3 }
value4 := convert.MapConverter.ToMap("ABC")                                                    // Returns {}
value5 := convert.MapConverter.ToMapWithDefault("ABC", *value2)                                // Returns {'key': 123}
value6 := convert.MapConverter.ToMapWithDefault(map[string]interface{}{"key": 12345}, *value2) // Returns {'key': 12345}

// Map converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = MapConverter.toNullableMap('ABC');                     // Returns null
var value2 = MapConverter.toNullableMap({'key': 123});              // Returns { key: 123 }
var value3 = MapConverter.toNullableMap([1, 2, 3]);                 // Returns { "0": 1, "1": 2, "2": 3 }
var value4 = MapConverter.toMap('ABC');                             // Returns {}
var value5 = MapConverter.toMapWithDefault('ABC', value2!);         // Returns {'key': 123}
var value6 = MapConverter.toMapWithDefault({'key': 12345}, value2); // Returns {'key': 12345}


# Map converter

from pip_services3_commons.convert import MapConverter

value1 = MapConverter.to_nullable_map("ABC")                        # Returns None
value2 = MapConverter.to_nullable_map({ 'key': 123 })               # Returns { key: 123 }
value3 = MapConverter.to_nullable_map([1,2,3])                      # Returns { "0": 1, "1": 2, "2": 3 }
value4 = MapConverter.to_map("ABC")                                 # Returns {}
value5 = MapConverter.to_map_with_default("ABC", value2)            # Returns {'key': 123}
value6 = MapConverter.to_map_with_default({ 'key': 12345 }, value2) # Returns {'key': 12345}

Not available
RecursiveMapConverter
Method Description
to_map Converts a value into a map object or returns an empty map when the conversion is not possible.
to_map_with_default Converts a value into a map object or returns a default value when the conversion is not possible.
to_nullable_map Converts a value into a map object or returns None when the conversion is not possible.
// Recursive map
import { RecursiveMapConverter } from "pip-services3-commons-nodex";

let value1 = RecursiveMapConverter.toMap({ "key": 123});                              // Returns {'key': 123}
let value2 = RecursiveMapConverter.toMapWithDefault(null, { "my key": "my val" });    // Returns { "my key": "my val" }
let value3 = RecursiveMapConverter.toNullableMap({ "key": 123 });                     // Returns {'key': 123}
let value4 = RecursiveMapConverter.toNullableMap([1,[2,3]]); // Returns {0: 1, 1: {0: 2, 1: 3}}

// Recursive map
using PipServices3.Commons.Convert;

var value1 = RecursiveMapConverter.ToMap(new Dictionary<string, object>() { { "key", 123 } });              // Returns {'key': 123}
var value2 = RecursiveMapConverter.ToMapWithDefault(null, new Dictionary<string, object>() { { "my key", "my val" } });   // Returns { "my key": "my val" }
var value3 = RecursiveMapConverter.ToNullableMap(new Dictionary<string, object>() { { "key", 123 } });     // Returns {'key': 123}
var value4 = RecursiveMapConverter.ToNullableMap(new List<object> { 1, new List<object> { 2, 3 } }) ;         // Returns {0: 1, 1: {0: 2, 1: 3}}

// Recursive map

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.RecursiveMapConverter.ToMap(map[string]interface{}{"key": 123})                                     // Returns {'key': 123}
value2 := convert.RecursiveMapConverter.ToMapWithDefault(nil, map[string]interface{}{"my key": "my val"}) // Returns {"my key": "my val"}
value3 := convert.RecursiveMapConverter.ToNullableMap(map[string]interface{}{"key": 123})                             // Returns {'key': 123}
value4 := convert.RecursiveMapConverter.ToNullableMap([]interface{}{1, []int{2, 3}})                                  // Returns {0: 1, 1: {0: 2, 1: 3}}
// Recursive map
import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = RecursiveMapConverter.toMap({'key': 123});                          // Returns {'key': 123}
var value2 = RecursiveMapConverter.toMapWithDefault(null, {'my key': 'my val'}); // Returns { "my key": "my val" }
var value3 = RecursiveMapConverter.toNullableMap({'key': 123});                  // Returns {'key': 123}
var value4 = RecursiveMapConverter.toNullableMap([[1,[2, 3]]]);                  // Returns {0: 1, 1: {0: 2, 1: 3}}

# Recursive map
from pip_services3_commons.convert import RecursiveMapConverter

value1 = RecursiveMapConverter.to_map({ 'key': 123 })              # Returns {'key': 123}
value2 = RecursiveMapConverter.to_map_with_default(None, { "my key": "my val" })   # Returns { "my key": "my val" }
value3 = RecursiveMapConverter.to_nullable_map({ 'key': 123 })     # Returns {'key': 123}
value4 = RecursiveMapConverter.to_nullable_map([1,[2,3]])          # Returns {0: 1, 1: {0: 2, 1: 3}}
Not available

11) TypeConverter

This class is used to convert arbitrary values into objects specified by a TypeCode and to get the TypeCode of an object. Its methods are explained in the table and examples below. Note: Code types are defined in the TypeCode class available in the same package.

Method Description
to_nullable_type Converts a value into an object type specified by a TypeCode or returns None when the conversion is not possible.
to_string Converts a TypeCode into its string name.
to_type Converts a value into an object type specified by a TypeCode
to_type_code Gets the TypeCode for a specific value.
to_type_with_default Converts a value into an object type specified by TypeCode or returns a default value when the conversion is not possible.
// Type converter

import { TypeCode, TypeConverter } from "pip-services3-commons-nodex";

let value1 = TypeConverter.toType(TypeCode.String, 123);                  // Returns '123'
let value2 = TypeConverter.toNullableType(TypeCode.String, 123);          // Returns '123'
let value3 = TypeConverter.toTypeWithDefault(TypeCode.Integer, "ABC", 1); // 1
let value4 = TypeConverter.toTypeCode("Hello world");                     // Returns TypeCode.String
let value5 = TypeConverter.toString(TypeCode.String);                     // Returns 'string'

// Type converter

using PipServices3.Commons.Convert;

var value1 = TypeConverter.ToType<string>(123);              // Returns '123'
var value2 = TypeConverter.ToTypeWithDefault<int>("ABC", 1); // 1
var value3 = TypeConverter.ToTypeCode("Hello world");        // Returns TypeCode.String
var value4 = TypeConverter.ToString(PipServices3.Commons.Convert.TypeCode.String); // Returns 'string'

// Type converter

import (
	"fmt"
	convert "github.com/pip-services3-gox/pip-services3-commons-gox/convert"
)

value1 := convert.TypeConverter.ToType(convert.String, 123)                  // Returns '123'
value2 := convert.TypeConverter.ToNullableType(convert.String, 123)          // Returns '123'
value3 := convert.TypeConverter.ToTypeWithDefault(convert.Integer, "ABC", 1) // Returns 1
value4 := convert.TypeConverter.ToTypeCode("Hello world")                    // Returns TypeCode.String
value5 := convert.TypeConverter.ToString(convert.String)                     // Returns 'string'
// Type converter

import 'package:pip_services3_commons/pip_services3_commons.dart';

var value1 = TypeConverter.toType(TypeCode.String, 123);                  // Returns '123'
var value2 = TypeConverter.toNullableType(TypeCode.String, 123);          // Returns '123'
var value3 = TypeConverter.toTypeWithDefault(TypeCode.Integer, 'ABC', 1); // 1
var value4 = TypeConverter.toTypeCode('Hello world');                     // Returns TypeCode.String
var value5 = TypeConverter.asString(TypeCode.String);                     // Returns 'String'

# Type converter

from pip_services3_commons.convert import TypeCode

value1 = TypeConverter.to_type(TypeCode.String, 123)             # Returns '123'
value2 = TypeConverter.to_nullable_type(TypeCode.String, 123)    # Returns '123'
value3 = TypeConverter.to_type_with_default(TypeCode.Integer, 'ABC', 1)    # 1
value4 = TypeConverter.to_type_code("Hello world")               # Returns TypeCode.String
value5 = TypeConverter.to_string(TypeCode.String)                # Returns 'string'
Not available

Wrapping up

In this tutorial, we have seen several components that provide methods with conversion mechanisms for arrays, Booleans, dates, doubles, floats, integers, longs, strings, JSON objects, maps and types defined by a type code.