Skip to content

Instantly share code, notes, and snippets.

@ghsatpute
Last active August 31, 2020 15:37
Show Gist options
  • Save ghsatpute/30114d983531e75cd0895ccbd118dc81 to your computer and use it in GitHub Desktop.
Save ghsatpute/30114d983531e75cd0895ccbd118dc81 to your computer and use it in GitHub Desktop.
Python mapping object to JSON

Python mapping object to json and vice versa

class School(object):
    def __init__(self, students: List[Student], online: bool):
        self.students: List[Student] = students
        self.online: bool = online

    def __repr_json__(self):
        return self.__dict__
class Student:
   def __init__(self, name: string, student_type: StudentType):
       self.students: List[Student] = students
       self.student_type: StudentType = student_type
class StudentType(Enum):
   REGULAR = 'REGULAR'
   PART_TIME = 'PART_TIME'

   def __str__(self):
       return '%s' % self.value
class SchoolMapper(object):
   @staticmethod
   def map_school(school_json: str) -> School:
       j: dict = json.loads(school_json)
       students = School.map_student(j.get('students'))
       del j['students']
       return School(students=students, **j)

   @staticmethod
   def map_student(student_dict: dict) -> JobSettings:
       return Student(**student_dict)
class ComplexEncoder(json.JSONEncoder):
   def default(self, obj):
       if isinstance(obj, Enum):
           return obj.__str__()
       if hasattr(obj, '__repr_json__'):
           return obj.__repr_json__()

       return json.JSONEncoder.default(self, obj)
class TestSchoolMapper(TestCase):
   def test_map_school(self):
       post_job_dto = self._create_dummy_school()
       json_str = json.dumps(post_job_dto,
                             cls=ComplexEncoder)

       mapped_school: School = SchoolMapper.map_school(json_str) 
       
       
   def _create_dummy_school():
       student1: Student = new Student("George", StudentType.REGULAR)
       student2: Student = new Student("Kevin", StudentType.PART_TIME)
       school: School = new School('Modern School', [student1, student2]); 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment