Extend what Pipeline can serialize.

  Args:
    object_type: type of the object.
    encoder: a function that takes in an object and returns
      a dict of json primitives.
    decoder: inverse function of encoder.
10769
def _register_json_primitive(object_type, encoder, decoder):
  
  global _TYPE_TO_ENCODER
  global _TYPE_NAME_TO_DECODER
  if object_type not in _TYPE_TO_ENCODER:
    _TYPE_TO_ENCODER[object_type] = encoder
    _TYPE_NAME_TO_DECODER[object_type.__name__] = decoder
168171
def type_handler_object(val, objtype):
    
    handler = handlers.get(objtype)
    if handler:
        return handler().restore(val)
    else:
        return objtype(val)
386705
def json_decoder_to_deserializer(decoder_cls: Union[Type[JSONDecoder], Callable[[], Type[JSONDecoder]]]) \
        -> Type[Deserializer]:
    
    name = decoder_cls.__name__ if isinstance(decoder_cls, type) else "%sLambdaTypeReturn" % id(decoder_cls)
    return type(
        "%sAsDeserializer" % name,
        (_JSONDecoderAsDeserializer,),
        {
            "decoder_type": property(lambda self: decoder_cls if isinstance(decoder_cls, type) else decoder_cls())
        }
    )
1095082
def json_encoder_default(obj):
    
    if np is not None and hasattr(obj, 'size') and hasattr(obj, 'dtype'):
        if obj.size == 1:
            if np.issubdtype(obj.dtype, np.integer):
                return int(obj)
            elif np.issubdtype(obj.dtype, np.floating):
                return float(obj)

    if isinstance(obj, set):
        return list(obj)
    elif hasattr(obj, 'to_native'):
        # DatastoreList, DatastoreDict
        return obj.to_native()
    elif hasattr(obj, 'tolist') and hasattr(obj, '__iter__'):
        # for np.array
        return obj.tolist()

    return obj
820242
def encode(self, object_):
        
        if self.enforce_reversible:
            self.enforce_reversible = False
            if self.decode(self.encode(object_)) != object_:
                raise ValueError('Encoding is not reversible for "%s"' % object_)
            self.enforce_reversible = True

        return object_
486183
def load_func(serializer_type):
    

    def outer_wrapper(loader_func):
        def wrapper(*args, **kwargs):
            return _load(
                *args,
                loader_func=loader_func, serializer_type=serializer_type,
                **kwargs
            )

        return wrapper

    return outer_wrapper
1146031
def _encode(self, obj, context):
        
        func = getattr(obj, 'to_construct', None)
        if callable(func):
            return func(context)
        else:
            return obj
1269698
def _write_object(self, val, outstream):
        '''
        
        '''
        # first attempt using an existing custom serializer
        serializer = self.__lookup_serializer(getattr(val, '__class__'))
        if serializer is not None:
            serializer.serialize(self, val, outstream)
            return
        
        fields = self._fetch_obj_fields(val)
        validfields = [];
        encodedfields = []
        length = 0;
        for f in fields:
            encoded = self._encode_field_name(val, f)
            if encoded:
                encodedfields.append(encoded)
                validfields.append(f)
                length += 1;
        self.write_object_start(length, outstream)
        count = 0;
        if length > 0:
            mappedname = encodedfields[0]
            if mappedname is not None:
                count += 1
                self.write_object_field(mappedname, getattr(val, validfields[0]), outstream)
            idx = 1
            while idx < length:      
                name = validfields[idx]
                mappedname = encodedfields[idx]
                if mappedname is not None:
                    value = getattr(val, name)
                    if count > 0:
                        self.write_object_field_separator(mappedname, value, outstream)
                    self.write_object_field(mappedname, value, outstream)
                    count += 1
                idx += 1
        self.write_object_end(length, outstream)
214944
def dump(obj, f, preserve=False):
    
    if not f.write:
        raise TypeError('You can only dump an object into a file object')
    encoder = Encoder(f, preserve=preserve)
    return encoder.write_dict(obj)
614978
def batch_encode(self, iterator, *args, **kwargs):
        
        return [self.encode(object_, *args, **kwargs) for object_ in iterator]
82061
def register_json_encoder(self, encoder_type: type, encoder: JSONEncoder):
        
        self._json_encoders[encoder_type] = encoder
        return self
219076
def json_encode(obj):
    """"""
    try:
        return json_encode.encoder.encode(obj)
    except AttributeError:
        json_encode.encoder = DjangoJSONEncoder(default=six.text_type)
        return json_encode(obj)
1312805
def encode_payload(cls, payload):
        ''''''
        try:
            return json.dumps(payload).encode()
        except TypeError:
            msg = f'JSON payload encoding error: {payload}'
            raise ProtocolError(cls.INTERNAL_ERROR, msg) from None
220433
def serialize(self, elt, sw, pyobj, **kw):
        '''
        '''
        if isinstance(pyobj, TypeCode):
            raise TypeError, 'pyobj is a typecode instance.'
        
        what = getattr(pyobj, 'typecode', None)
        if what is not None and type(pyobj) is types.InstanceType:
            tc = pyobj.__class__
            what = Any.serialmap.get(tc)
            if not what:
                tc = (types.ClassType, pyobj.__class__.__name__)
                what = Any.serialmap.get(tc)
        
        self.logger.debug('processContents: %s', self.processContents)

        # failed to find a registered type for class
        if what is None:
            #TODO: seems incomplete.  what about facets.
            #if self.processContents == 'strict':
            what = Any(pname=(self.nspname,self.pname))
                
        self.logger.debug('serialize with %s', what.__class__.__name__)
        what.serialize(elt, sw, pyobj, **kw)
524598
def build(self) -> type:
        
        def _get_property_mappings(encoder: MappingJSONEncoder) -> List[JsonPropertyMapping]:
            return _get_all_property_mappings(encoder, self.mappings, self.superclasses)

        def get_serializable_cls(encoder: MappingJSONEncoder) -> type:
            return self.target_cls

        def default(encoder: MappingJSONEncoder, serializable):
            if serializable is None:
                # Fix for #18
                return None
            elif isinstance(serializable, List):
                # Fix for #8
                return [encoder.default(item) for item in serializable]
            else:
                # Sort subclasses so subclass' default method is called last
                superclasses_as_list = list(self.superclasses)
                superclasses_as_list.sort(key=lambda superclass: 1 if superclass == MappingJSONEncoder else -1)

                encoded_combined = {}
                for superclass in superclasses_as_list:
                    encoded = superclass.default(encoder, serializable)
                    encoded_combined.update(encoded)

                return encoded_combined

        return type(
            "%sDynamicMappingJSONEncoder" % self.target_cls.__name__,
            self.superclasses,
            {
                "_get_property_mappings": _get_property_mappings,
                "_get_serializable_cls": get_serializable_cls,
                "default": default
            }
        )
1118554
def dump(obj, fp, **user_kwargs):
    
    return json.dump(obj, fp, **_encoder_kwargs(user_kwargs))
824262
def _encode(self, obj):
        

        if self._use_hook:
            obj = self.encode_hook(obj)

        # first try simple strict checks

        _objtype = obj.__class__

        if _objtype is str:
            return self._encode_str(obj)

        if _objtype is bool:
            if obj:
                return 'true'
            else:
                return 'false'

        if _objtype is int or _objtype is float:
            return self._encode_numbers(obj)

        if _objtype is list or _objtype is tuple:
            return self._encode_list(obj)

        if obj is None:
            return 'null'

        if _objtype is dict or obj is OrderedDict:
            return self._encode_dict(obj)

        if _objtype is UUID:
            return '"' + str(obj) + '"'

        if _objtype is Decimal:
            return '"' + str(obj) + '"'

        # For all non-std types try __mm_json__ and then __mm_serialize__ before any isinstance
        # checks

        try:
            sx_json_data = obj.__mm_json__
        except AttributeError:
            pass
        else:
            try:
                data = sx_json_data()
            except NotImplementedError:
                pass
            else:
                if isinstance(data, bytes):
                    return data.decode('utf-8')
                else:
                    return self._encode_str(data, escape_quotes=False)
        try:
            sx_encoder = obj.__mm_serialize__
        except AttributeError:
            pass
        else:
            try:
                data = sx_encoder()
            except NotImplementedError:
                pass
            else:
                return self._encode(data)

        # do more in-depth class analysis

        if isinstance(obj, UUID):
            return '"' + str(obj) + '"'

        if isinstance(obj, str):
            return self._encode_str(obj)

        if isinstance(obj, (list, tuple, set, frozenset, Set)):
            return self._encode_list(obj)

        if isinstance(obj, Sequence) and not isinstance(obj, (bytes, bytearray)):
            return self._encode_list(obj)

        if isinstance(obj, (dict, OrderedDict, Mapping)):
            return self._encode_dict(obj)

        # note: number checks using isinstance should come after True/False checks
        if isinstance(obj, Number):
            return self._encode_numbers(obj)

        if isinstance(obj, (date, time)):
            return '"' + obj.isoformat() + '"'

        return self._encode(self.default(obj))