这可能是您使用 Python 内置 JSON 库的解决方案,该库利用 Python 将字典作为关键字参数提取的能力。
我根据您的大纲在 Python 中定义了类。在 User 类定义中,我允许将地址作为实际地址对象、列表(从 JSON 数组转换而来)或字典(从 JSON 对象转换而来)传递。
class Address(object):
def __init__(self, addressFirstLine, city, pincode):
self.addressFirstLine = addressFirstLine
self.city = city
self.pincode = pincode
class User(object):
def __init__(self, firstName, lastName, address):
self.firstName = firstName
self.lastName = lastName
if isinstance(address, Address):
self.address = address
elif isinstance(address, list):
self.address = Address(*address)
elif isinstance(address, dict):
self.address = Address(**address)
else:
raise TypeError('address must be provided as an Address object,'
' list, or dictionary')
我使用内置的 Python json 库将您提供的 JSON 字符串转换为字典,然后使用该字典创建用户对象。正如您在下面看到的,user.address 是一个实际的地址对象(我在一个名为 user_address.py 的文件中定义了用户和地址,因此是前缀)。
>>> import json
>>> user_dict = json.loads('{
"firstName" : "Zen", "lastName" : "Coder",
"address" : {
"addressFirstLine" : "High st, Point place",
"city" : "Wisconcin",
"pincode" : "4E23C"}
}')
>>> from user_address import User
>>> user = User(**user_dict)
>>> user
<user_address.User at 0x1035b4190>
>>> user.firstName
u'Zen'
>>> user.lastName
u'coder'
>>> user.address
<user_address.Address at 0x1035b4710>
>>> user.address.addressFirstLine
u'High st, Point place'
>>> user.address.city
u'Wisconcin'
>>> user.address.pincode
u'4E23C'
此实现还支持拥有地址参数列表,而不是字典。如果传递了不受支持的类型,它还会引发描述性错误。
>>> user_dict = json.loads('{
"firstName" : "Zen", "lastName" : "coder",
"address" : ["High st, Point place", "Wisconcin", "4E23C"]
}')
>>> user = User(**user_dict)
>>> user.address
<user_address.Address at 0x10ced2d10>
>>> user.address.city
u'Wisconcin'
>>> user_dict = json.loads('{
"firstName" : "Zen", "lastName" : "coder",
"address" : "bad address"
}')
TypeError: address must be provided as an Address object, list, or dictionary
这个另一个答案还谈到了将 Python dict 转换为 Python 对象,使用更抽象的方法:Convert Python dict to object