我有一个 Properties 类:
from child_props import ChildProps
class ParentProps(object):
"""Contains all the attributes for CreateOrderRequest"""
def __init__(self):
self.__prop1 = None
self.__child_props = ChildProps()
@property
def prop1(self):
return self.__prop1
@prop1.setter
def prop1(self, value):
self.__prop1 = value
@property
def child_props(self):
return self.__child_props
@child_props.setter
def child_props(self, value):
self.__child_props = value
另一个类是:
class ChildProps(object):
"""Contains all the attributes for CreateOrderRequest"""
def __init__(self):
self.__child_prop1 = None
self.__child_prop2 = None
@property
def child_prop1(self):
return self.__child_prop1
@child_prop1.setter
def child_prop1(self, value):
self.__child_prop1 = value
@property
def child_prop2(self):
return self.__child_prop2
@child_prop2.setter
def child_prop2(self, value):
self.__child_prop2 = value
在main.py文件中。
parent_props = ParentProps()
parent_props.prop1 = "Mark"
child_props = ChildProps()
child_props.child_prop1 = 'foo'
child_props.child_prop2 = 'bar'
parent_props.child_props = child_props
如何将parent_props序列化为以下json字符串:
{
"prop1" : "Mark",
"child_props" : {
"child_prop1" : "foo",
"child_prop2" : "bar"
}
}
PS: json.dumps只能序列化本地的Python数据类型。pickle模块只对对象进行字节级别的序列化。
就像在dotnet中我们有NewtonSoft,在Java中有jackson一样,Python中用于序列化getter/setter属性类对象的等效序列化程序是什么。
我在Google上搜索了很多,但没有得到太多帮助。任何线索将不胜感激。谢谢
json.dumps
该字典。 - abarnert@property
、__init__
和JSON序列化,但SO不是询问库推荐的好地方。如果这是你想要的,而且你在搜索中找不到它,请尝试访问python.org网站上的社区部分(可能是python-list邮件列表或#python IRC频道)。 - abarnert