Python2.7 自定义类的序列化与反序列号
关于自定义类的序列化与反序列化,有一篇博客介绍的方法比较通用:
https://www.cnblogs.com/magic8sky/p/10475704.html
但是这个方法在Python2.7中好像有问题(同时没有验证Python3中是否OK),在这里介绍一种方法,但是并不是非常好,需要针对每个自定义类编写特定的序列化、反序列化类。
下面的代码用于将一个List对象(元素是FolderInfo对象)进行序列化与反序列化。
FolderInfo.py
import json class FolderInfo: root = "" fileList = [] def __init__(self): pass def toJson(self): overdict = self.__dict__ # result = json.dumps(overdict, ensure_ascii=False) result = json.dumps(overdict) return result
FolderInfoListDecoder.py
from FolderInfo import FolderInfo import json class FolderInfoListDecoder(json.JSONDecoder): def decode(self, s): folderInfoes = [] folderInfoListObj = super(FolderInfoListDecoder, self).decode(s) for folderInfoStr in folderInfoListObj: folderInfo = FolderInfo() folderInfoObj = super(FolderInfoListDecoder, self).decode(folderInfoStr) for k, v in folderInfoObj.iteritems(): if k == "root": folderInfo.root = v elif k == "fileList": folderInfo.fileList = v folderInfoes.append(folderInfo) return folderInfoes
FolderInfoListEncoder.py
from FolderInfo import FolderInfo import json class FolderInfoListEncoder(json.JSONEncoder): def default(self, field): if isinstance(field, FolderInfo): return field.toJson() else: return json.JSONEncoder.default(self, field)
反序列化
folderInfoList = json.loads(folderInfoListJson, cls=FolderInfoListDecoder)
序列化
fileInfoListJson = json.dumps(folderInfoList, cls=FolderInfoListEncoder)