.. _module_ext_datagen_serializer:

Serializer
==========

This sections contains module documentation of serializer module.

serializer
^^^^^^^^^^

Module provides class Serializer for class serializion to various formats.
Unit tests available at hydratk/extensions/datagen/serializer/01_methods_ut.jedi

All methods are static. The methods support special class attributes (optional, see example).

* _order - list of instance attributes names, it defines serialization order, missing attributes are omitted (not serialized)
* _naming - dictionary (key - attribute name, value - new name used in serialization) 

**Sample classes** :

  .. code-block:: python
  
     class tst():
    
         _order = ['_a', '_b', '_c', '_d', '_e', '_f', '_g', '_h', '_i']
         _naming = {'_a':'a', '_b':'b', '_c':'c', '_d':'d', '_e':'e', '_f':'f', '_g':'g', '_h':'h', '_i':'i'}
    
         def __init__(self):
        
             self._a = 'a'
             self._b = 'b'
             self._c = 1
             self._d = tst2() 
             self._e = [1, 2, 3]
             self._f = ('a', 'b')   
             self._g = {'a':'1'}    
             self._h = [tst2(), tst2()]
             self._i = {'test1': tst2()}
    
     class tst2():
    
         _order = ['_y', '_x']
         _naming = {'_x':'x', '_y':'y'}
    
         def __init__(self):
        
             self._x = 'x'
             self._y = 2 

**Methods** :

* tostr

Method serializes given object instance to indented string.

  .. code-block:: python
  
     from hydratk.extensions.datagen.serializer import Serializer
     
     res = Serializer.tostr(tst())

* toxml

Method serializes given object instance to xml string, it uses lxml method tostring with indentation (xml object is generated by method from string). 

  .. code-block:: python
     
     res = Serializer.toxml(tst())

* tojson

Method serializes given object instance to json string, it uses simplejson method dumps with indentation. 
It is not supported for Python 2.6 (missing OrderedDict), raises NotImplementedError.

  .. code-block:: python
     
     res = Serializer.tojson(tst())

* _get_attrs

Auxiliary method, it returns instance attributes as dictionary.

* _has_attrs

Auxiliary method, it checks if instance has some attributes.

* _tostr

Auxiliary method, it serializes given object to string. Method is called recursively within class traversal.
Method automatically indents each level with two spaces. It uses class attributes _order, _naming during serialization.

* _toxml

Auxiliary method, it serializes given object to xml string. Method is called recursively within class traversal.
It uses class attributes _order, _naming during serialization.

* _tojson

Auxiliary method, it serializes given object to ordered dictionary. Method is called recursively within class traversal.
It uses class attributes _order, _naming during serialization.