Created
October 16, 2014 14:59
-
-
Save xianmin/c1498d0520dbc492cdf9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import json | |
from decimal import Decimal | |
class MyEncoder(json.JSONEncoder): | |
def default(self, obj): | |
data = {'__class__': obj.__class__.__name__, | |
'__module__': obj.__class__.__module__, | |
} | |
if hasattr(obj, '__dict__'): | |
data.update(obj.__dict__) | |
if isinstance(obj, Decimal): | |
data.update({'Decimal': float(obj)}) | |
return data | |
class MyDecoder(json.JSONDecoder): | |
def __init__(self): | |
json.JSONDecoder.__init__(self, object_hook=self.dict_to_object) | |
def dict_to_object(self, d): | |
if '__class__' in d: | |
inst = None | |
class_name = d.pop('__class__') | |
module_name = d.pop('__module__') | |
module = __import__(module_name) | |
class_ = getattr(module, class_name) | |
if 'Decimal' in d: | |
arg = Decimal(d.pop('Decimal')) | |
inst = class_(arg) | |
else: | |
args = dict((key.encode('ascii'), value) | |
for key, value in d.items()) | |
inst = class_(**args) | |
else: | |
inst = d | |
return inst | |
class MyTest(object): | |
def __init__(self, name): | |
self.name = name | |
# 测试 | |
mytest = [Decimal(3.3), [1, 2, 3], {'a': 1, 'b': 2}, | |
MyTest({'a': 1, 'b': 2}), MyTest(Decimal(3.3))] | |
test_encode = MyEncoder().encode(mytest) | |
print test_encode | |
test_decode = MyDecoder().decode(test_encode) | |
print test_decode |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment