# Jaxer.Serialization : Object
Return to: Jaxer Framework index

This is the namespace that contains Jaxer serialization methods. The Jaxer serializer uses the familiar and popular JSON format. However, additional functionality has been provided to allow for serialization of more complex data structures. Specifically, this module supports cyclical data structures, multiple references, and custom serializers. Each of these is described below. Cyclical data structures occur when an object (or array) contains a descendent structure that also references that same object. For example, a DOM node has references to its children and these children also have references to the DOM node (their parentNode). In a traditional JSON environment, if you were to try to serialize this structure, you would end up in an infinite loop as the serializer traversed the parent node, its child nodes, and then back up to the parent node through the child's parentNode property. Indeed, the serializer couldn't get past the first child in this scenario. The Jaxer serializer gets around this via specially formatted strings referred to as "references". Multiple references are similar to cyclical data structures in that an object is referenced two or more times. However, this does not necessarily create a cycle. For example, say you have the following code:

    var car = { color: "blue", price: 10000 }; var cars = [ car, car ] ;

As you can see, the same car object has been referenced twice in the array. In a traditional JSON serializer, each instance of car would be serialized separately. Unfortunately, that alters the data structure that will be accessed after deserialization. You will end up with two independent car objects which means that changing the price of one will not change the price of the other as would have happened before the serialization/deserialization cycle. In order to restore the same references, Jaxer serializes the car only once and then leaves placeholders to point to that single serialization instance. During deserialization, the placeholders are replaced with references to the deserialized object, thus restoring the original data structure. Some data types cannot be expressed in JSON. For example, the Date type is not listed as a valid type in JSON. So, in order to support this type and potentially many others, the serializer allows the developer to register custom serializers and associated deserializers for a given type. When the serializer sees these types, the custom handlers are used to convert the item to a string. It is then the responsibility of the custom deserializer to restore the item to its original structure, as appropriate. For example, Jaxer supports XMLDocuments. The custom serializer creates an XML string which is specially tagged so the deserializer can restore the XML string back to an XMLDocument. Next, we briefly discuss how Jaxer recognizes cycles, multi-references, and how it represents references and custom serialized objects. The Jaxer serializer makes an initial pass over the data being serialized. Each object, array, and custom serialization object is tagged with a unique index. (Note that some objects do not allow properties to be added to them. In this situation, the Jaxer serializer maintains an array of these items. This array is searched when new items are encountered and serves the same purpose as the id property). Before adding the index, we first check if we have already indexed the item. If the tag already exists, then we've either exposed a cycle or a multi-reference. At this point, the serializer knows to switch to another JSON format that minimizes the amount of data to be serialized. References and custom serialization objects each make use of specially formatted strings. To make this a bit clearer, we create an array of two references to the same date object.

    var d = new Date(); var items = [ d, d ] ; var json = Jaxer.Serialization.toJSONString(items);

The resulting JSON string will look like the following:

     [ [ "~1~","~1~" ] , "~Date:2007-08-17T11:57:30~" ]

This format always has a top-level array whose first element is the root item that was originally being serialized. In this case, our top-most element was an array. As an aside, the only top-level elements that can generate this format are arrays, objects, and custom serialization objects. The first special format used for references and is defined with "~ # ~" where # is a number. The number is the index into the top-level array. The element at that index is the item that needs to be referenced where the reference string lives. In this example, once deserialization has completed, both instances of "~1~" will have been replaced with references to the deserialized date object. The next custom format, the date, shows how custom serializers emit text. The first item after the ~ but before the : is the name of the type. This is the fully-qualified type as you would have to type it in JavaScript to get to that type's constructor. The string after the : is in a format as generated by the type's custom serializer. The resulting string generated by the custom serializer is in turn serialized as a string, so the deserializer does not need to handle special characters or escape sequences. It is the responsibility of the custom deserializer to consume that text and to return effectively a clone of the original object. This module also allows a developer to register alternate serialization and deserialization methods. The default method as described above is referred to as the "jaxer" method. Alternately, if you require strict adherence to pure JSON, you can use the "json" method. The method is specificed in a separate optional parameter to the "toJSONString" function (see that function for more details).

## Platform Support

Jaxer Server Framework | Jaxer Client Framework
--- | ---
1.0 | 1.0

## Functions

Method | Action | Jaxer Server Framework | Jaxer Client Framework
--- | --- | --- | ---
static addDeserializer(String name, Function deserializer, [Function beforeDeserialization,] [Function afterDeserialization]) : void Add a top-level JSON serializer | Show Details | 1.0 | 1.0

Parameters

String | name | The unique name of the deserializer. This name can be specified in the options object provided to the fromJSONString function. That will select this deserializer as the top-level function to deserialize the specified object. Note that case is not significant
Function | deserializer | The function used to deserialized the JSON string created by the associated serializer.

Function

beforeDeserialization

(optional)An optional function that will be called before the top-level deserialization process begins. This function should take a single parameter which will be the options object provided to the fromJSONString function. Note that the options object will be an inherited clone of the object sent to fromJSONString. This allows this function to initialize any data structures needed by the deserializer without altering the original options object passed into fromJSONString

Function | afterDeserialization | (optional)An optional function that will be called after the top-level deserialization process ends. This function should take a single parameter which will be the options object provided to the fromJSONString function. Note that the options object will be an inherited clone of the object sent to the fromJSONString.

static addSerializer(String name, Function serializer, [Function beforeSerialization,] [Function afterSerialization]) : void Add a top-level JSON serializer | Show Details | 1.0 | 1.0

Parameters

String | name | The unique name of the serializer. This name can be specified in the options object provided to the toJSONString function. That will select this serializer as the top-level function to serialize the specified object. Note that case is not significant
Function | serializer | The function used to serialize data. This function should take two arguments: the actual data to serialize and an options object

Function

beforeSerialization

(optional)An optional function that will be called before the top-level serialization process begins. This function should take a single parameter which will be the options object provided to the toJSONString function. Note that the options object will be an inherited clone of the object sent to the toJSONString. This allows this function to initialize any data structures needed by the serializer without altering the original options object passed into toJSONString

Function | afterSerialization | (optional)An optional function that will be called after the top-level serialization process ends. This function should take a single parameter which will be the options object provided to the toJSONString function. Note that the options object will be an inherited clone of the object sent to the toJSONString.

static addTypeHandler(String name, Function serializer, Function deserializer, [Function canSerialize,] [Function canDeserialize]) : void Add handlers for custom serialization/deserialization | Show Details | 1.0 | 1.0

Parameters

String | name | The fully-qualified name of the type. This should reflect the full, potentially dotted, notation you would need to use to access this type's constructor from the global context.
Function | serializer | A function that takes an instance of the type it serializes and that returns a string representation of the type suitable as input into the deserializer
Function | deserializer | A function that takes a string produced by the custom serializer and that returns a new instance of the custom supported type.
Function | canSerialize | (optional)An optional function that takes an object instance and returns a boolean. This function should return true if it the current handler is able to serialize the object passed to it.
Function | canDeserialize | (optional)An optional function that takes an object instance and returns a boolean. This function should return true if it the current handler is able to deserialize the string passed to it.

static fromJSONString(String json, Object options) : Object
Reconstruct a Javascript data structure from a JSON string. Note that we have extended JSON to support object references and to support dates. Object references allow multiple places within the JSON data structure to point to the same object as opposed to clones of those objects. Date support uses a special string format to store a given date in GMT

Show Details

1.0

1.0

Parameters

String | json | A string in the JSON format
Object | options | The options objecct which can be used to control deserialization

Returns

Object | The resulting object graph after converting the JSON string to the equivalent Javascript data structure

static removeSerializer(String name) : Boolean Remove support for the custom JSON serializer | Show Details | 1.0 | 1.0

Parameters

String | name | The name of the serializer to remove. Note that case is not significant

Returns

Boolean | Returns true if the serializer was successfully removed. Note that this function will return false if you attempt to remove a handler that is not already registered or if it is a built-in serializer like "jaxer".

static removeTypeHandler(String name) : Boolean Remove support for custom serialization/deserialization for the specified type | Show Details | 1.0 | 1.0

Parameters

String | name | The fully qualified name of the type to remove

Returns

Boolean | Returns true if the handler was successfully removed. Note that this function will return false if you attempt to remove a handler that is not already registered.

static toJSONString(Object data, [Object options]) : String
Convert the specified object into a JSON representation. Note that we have modified JSON to support object references (cycles) and to convert Dates into a special format that will be recognized by our code during deserialization. This function includes an optional second parameter which can be used to control how the data is serialized. If the options parameter defines an 'as' property, the will be used to select the serialization format. Currently, the values 'jaxer' and 'json' are supported where 'jaxer' includes support for cycles, multi-refs, and custom type serializers and where 'json' follows the serialization format and semantics as defined by Douglas Crockford on the json.org website. When specifying the 'jaxer' serializer, additional options are available. The "useCustomSerializers" has a boolean value which defaults to true. When this property is true, any type serializers that have been registered via addTypeHandler will be used in the serialization process. When this value is false, items needing custom serialization will be ignored as they would be in the "json" format. The "undefinedSerializationAction" property determines how the 'undefined' value is handled. The action defaults to 'serialize', but 'throw' is also supported which will throw an exception when trying serialize 'undefined'. When specifying the 'json' serializer, additional options are available. The 'maxDepth' property, which defaults to 10, is used to prevent deep recursion. If the recursion level is encountered, the 'maxDepthAction' property determines the serializer's action. 'truncate' will emit a "__truncated__" string in place of the object that would cause the recursion level to be exceeded. 'throw' will throw an exception. The 'dateSerializationAction' property is used to determine how dates are processed. A value of 'serialize' will convert the date to a specially formatted string as described in the json.org example code. A value of 'throw' will throw an exception when a date is encountered. The 'undefinedSerializationAction' property is used to determine how 'undefined' is processed. A value of 'serialize' will convert the value to 'undefined'. 'throw' will throw an exception and 'nullify' will return 'null'. The 'specialNumberSerializationAction' property is used to determine how Infinity, -Infinity, and NaN are processed. A value of 'serialize' will convert the value to their text representation which is the same as the identifier used to represent them. 'throw' will throw an exception and 'nullify' will return null. Note that other serializers may be registered with Jaxer. Most likely those serializers will define their own set of options. You will need to refer to the implementors documentation to discover those properties, their value, and their associated semantics.

Show Details

1.0

1.0

Parameters

Object | data | The source object to convert to a JSON string
Object | options | (optional)An optional object used to specify configuration info to the selected serializer

Returns

String | The resulting JSON string which can be reversed back into the source object via Serialization.fromJSONString

aptana_docs