摘要
我有一个Python对象层次结构,我想使用JSON序列化(只需通过https://docs.python.org/3/library/json.html,而不是使用任何额外的第三方库)。我想排除某些字段/属性/子对象。我发现很难找到一个简单的答案来实现这个目标?在
示例
我将有一个派生类实例,结果如下:
class MyItemClass(BaseItemClass):
self.saveThisProperty = 999
self.dontSaveThisProperty = "Something"
self.saveThisObject = ObjectType1()
self.dontSaveThisObject = ObjectType2()
如果我序列化为XML,我希望它看起来像
^{pr2}$注意,我只序列化特定的属性/子对象,而且我不想序列化派生类实例的整个BaseItemClass
。在
在XML中我很好。我知道如何在处理我想要的内容时输出XML片段,要么输出到最后保存的临时内存中文档,要么以增量方式将各个节点/元素输出到流中。我不必把所有的东西都序列化。E、 g
xmlStream.writeStartElement("MyItemClass")
xmlStream.writeElementWithValue("saveThisProperty", 999)
xmlStream.writeStartElement("saveThisObject")
...
xmlStream.writeEndElement("saveThisObject")
xmlStream.writeEndElement("MyItemClass")
对于JSON我不能这么做,对吗?我是否需要创建一些新的“独立”对象层次结构(没有来自BaseClass
的派生),方法是只复制我想要的属性/子对象,然后JSON序列化它?在
我确实看到了json.dump(default = ...)
,但这说明:
If specified, default should be a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object
然而,并不是说原始对象不能按默认Python->JSON序列化,而是我不想那样默认,序列化所有行为,我想要我的“选择性”行为。在
我是手术室。我在这里张贴是为了澄清我在我的案件中使用了什么。在
我把@Sina Rezaei在这个帖子中的帖子标记为可接受的解决方案,因为这(他帖子的最后一部分)和@snakechamerb的评论启发我理解了需要什么。在
我的解决方案概要如下:
def json_dump_obj(self) -> dict:
方法。在json.dump(self, stream, default=ModelScene.json_serialize_dump_obj)
通过静态方法ModelScene.json_serialize_dump_obj
将访问的每个节点增量序列化为流。如果可用,则调用myobj.json_dump_obj()
,否则将调用基本对象类型的默认JSON序列化。在有趣的是,我遇到了一个和我有同样担心的人。从来看,两者有什么区别json.dump文件()和json.dumps文件()在python中?,解决方案https://stackoverflow.com/a/57087055/489865:
我可以为你的情况想出三种解决办法:
解决方案1: 使用Pykson第三方库并定义要序列化为pykson字段的字段。在
样品:
免责声明:我是pykson库的开发人员。在
解决方案2: 第二种解决方案是使用带有自定义默认反序列化程序的包装类。在
^{pr2}$解决方案3: 这可能是个坏主意,但是如果你有一个深层层次结构,你也可以添加一个函数到所有的C类中,这些类将被序列化,并使用这个函数来获取一个字典,并轻松地将字典转换为json。在
也可以使用默认处理程序获得相同的结果:
相关问题 更多 >
编程相关推荐