I am new to Python and learning python. I have a requirement where I need to convert Python object to Json String and Json String to Python object just like what we do in Jackson in Java. I am able to convert to Json String but while converting from json String to Python object, I am getting the following error.
AttributeError: 'dict' object has no attribute 'firstName'
I provide below the code details.
Employee Object as
import 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)
Country Object as
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
My test program is given below.
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()
What is the problem with this above code ? Please help me solve this. Besides I have few questions.
- Is there any framework in Python just like Jackson in Java to and from conversion ?
- How to achieve like @PropertyOrder("firstName","lastName","Country" ...etc) just like Jackson in java equivalent in python ?
Before posting this question, I have also gone through the following stackoverflow link How to make a class JSON serializable.