我在Java中定义了两个类。我们称他们为“用户”和“地址”
class Address {
String addressFirstLine;
String city;
String pincode;
// Getters/setters for all attributes
}
class User {
String firstName;
String lastName;
Address address;
// Getters/setters for all attributes
}
我创建了User类的对象,并使用Gson库对其进行了序列化。
JSON字符串类似于:
{"firstname":"Zen","lastName":"coder", "Address":{"addressFirstLine":"High st, Point place","city":"Wisconcin","pincode":"4E23C"}}
现在这个字符串被发送到一个python应用程序,该应用程序具有相同的两个类定义'User'和'Address',其定义与上面的Java完全相同。
我尝试使用jsonpickle将json反序列化为python对象。我可以使用jsonpickle而不是复杂的对象来反序列化简单对象。
有人可以建议解决这个问题吗?
答案 0 :(得分:1)
这可能是使用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是一个实际的Address对象(我在一个名为user_address.py的文件中定义了User和Address,因此是前缀)。
>>> 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