【发布时间】:2019-04-20 16:43:21
【问题描述】:
我是 Python 新手,正在学习 Python。我有一个要求,我需要将 Python 对象转换为 Json 字符串,将 Json 字符串转换为 Python 对象,就像我们在 Java 中的 Jackson 中所做的那样。我能够转换为 Json 字符串,但是在从 json 字符串转换为 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()
上面的代码有什么问题?请帮我解决这个问题。 另外我有几个问题。
- Python 中是否有任何框架,就像 Java 中的 Jackson 来回转换?
- 如何实现像 @PropertyOrder("firstName","lastName","Country" ...etc) 就像 java 中的 Jackson 在 python 中等效?
在发布这个问题之前,我还浏览了以下stackoverflow链接How to make a class JSON serializable。
【问题讨论】:
-
所有属性都不是必须的,使用普通属性即可。
-
请建议,我写的就像我们在 java 中使用 getter 和 setter 所做的那样。
-
也将所有内容放在一个文件中;每个文件一个类也仅限于 Java。
-
好的,接受了先生,能帮我解决这个问题吗?
-
您正在调用
emp1.firstName(),但emp1不是Employee对象。它只是存储转换后的 json,因此它是一个字典。您需要拨打emp.firstName(),但这不会达到您的预期目的。看看stackoverflow.com/questions/10252010/…