我是Python和学习python的新手。我有一个需要将Python对象转换为Json String和将Json String转换为Python对象的要求,就像我们在Java中的Jackson中所做的那样。我能够转换为Json String,但是从json String转换为Python对象时,出现以下错误。
AttributeError:“ dict”对象没有属性“ firstName”
我在下面提供了代码详细信息。
员工对象为
导入json
class Employee:
def __init__(self):
self._firstName = None
self._lastName = None
self._country = None
@property
def firstName(self):
return self._firstName
@firstName.setter
def firstName(self, fName):
self._firstName = fName
@property
def lastName(self):
return self._lastName
@lastName.setter
def lastName(self, lName):
self._lastName = lName
@property
def country(self):
return self._country
@country.setter
def country(self, contryObj):
self._country = contryObj
def toJSON(self):
return json.dumps(self, default=lambda o: o.__dict__,
sort_keys=True, indent=4)
def toEmployee(self, jsonString):
return json.loads(jsonString)
国家对象为
class Country:
def __init__(self):
self._countryName = None
self._countryCode = None
@property
def countryName(self):
return self._countryName
@countryName.setter
def countryName(self, cName):
self._countryName = cName
@property
def countryCode(self):
return self._countryCode
@countryCode.setter
def countryCode(self, cCode):
self._countryCode = cCode
下面给出了我的测试程序。
from toFromJson.Employee import Employee
from toFromJson.Country import Country
def checkEmp():
emp = Employee()
emp._firstName = "DD"
emp._lastName = "Mishra"
country = Country()
country.countryCode = "12345"
country.countryName = "India"
emp.country = country
print("Emp in toString format : ", emp.__dict__)
print("--------------------- IN JSON -----------------")
print(emp.toJSON())
jsonString = '{ "_country": { "_countryCode": "7896", "_countryName": "India" }, "_firstName": "John", "_lastName": "Abrham" }'
emp1 = emp.toEmployee(jsonString)
print("Employee Name : ", emp1.firstName())
print("Conveted object : ", emp1.__dict__)
if __name__ == "__main__":
checkEmp()
上面的代码有什么问题?请帮我解决这个问题。 除了我有几个问题。
在发布此问题之前,我还通过了以下stackoverflow链接How to make a class JSON serializable。
答案 0 :(得分:1)
您必须为json.loads
和json.dumps
定义钩子:
import json
class Employee:
def __init__(self, firstName=None, lastName=None, country=None):
self.firstName = firstName
self.lastName = lastName
self.country = country
class Country:
def __init__(self, countryName=None, countryCode=None):
self.countryName = countryName
self.countryCode = countryCode
def to_json(obj):
if isinstance(obj, Employee):
return {
'firstName': obj.firstName,
'lastName': obj.lastName,
'country': obj.country,
}
if isinstance(obj, Country):
return {
'countryName': obj.countryName,
'countryCode': obj.countryCode,
}
raise TypeError
def from_json(obj):
if 'firstName' in obj:
return Employee(**obj)
if 'countryName' in obj:
return Country(**obj)
return obj
def check_emp():
emp = Employee("DD", "Mishra", Country("India", "12345"))
json_string = json.dumps(emp, default=to_json, sort_keys=True, indent=4)
print(json_string)
emp1 = json.loads(k, object_hook=from_json)
print("Employee Name : ", emp1.firstName)
if __name__ == "__main__":
check_emp()