Changes between Initial Version and Version 1 of pyson


Ignore:
Timestamp:
04/21/21 16:28:01 (4 years ago)
Author:
wouter
Comment:

--

Legend:

Unmodified
Added
Removed
Modified
  • pyson

    v1 v1  
     1== Packson
     2
     3Packson is a json (de)serializer for python objects.
     4It uses annotations in the style of jackson.
     5
     6
     7The basic version determines the types for (de)serialization from the __init__ function in the involved classes. Polymorphism is supported, so derived classes can (de)serialized from a superclass.
     8
     9A complex example showing many things at once (I did not have time to write out many simpler examples)
     10
     11{{{
     12from jackson.ObjectMapper import ObjectMapper
     13from jackson.JsonSubTypes import JsonSubTypes
     14from jackson.JsonTypeInfo import JsonTypeInfo
     15from jackson.JsonTypeInfo import Id,As
     16from typing import Dict,List,Set
     17import json
     18
     19class Props:
     20    '''
     21    compound class with properties, used for testing
     22    '''
     23    def __init__(self, age:int, name:str):
     24        if age<0:
     25            raise ValueError("age must be >0, got "+str(age))
     26        self._age=age
     27        self._name=name;
     28    def __str__(self):
     29        return self._name+","+str(self._age)
     30    def getage(self):
     31        return self._age
     32    def getname(self):
     33        return self._name
     34    def __eq__(self, other):
     35        return isinstance(other, self.__class__) and \
     36            self._name==other._name and self._age==other._age
     37
     38
     39@JsonSubTypes(["test.ObjectMapperTest.Bear"])
     40@JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT)
     41class Animal:
     42    pass
     43   
     44   
     45class Bear(Animal):
     46    def __init__(self, props:Props):
     47        self._props=props
     48           
     49    def __str__(self):
     50        return "Bear["+str(self._props)+"]"
     51       
     52    def getprops(self):
     53        return self._props
     54    def __eq__(self, other):
     55        return isinstance(other, self.__class__) and \
     56            self._props==other._props
     57
     58jackson=ObjectMapper()
     59
     60
     61obj=Bear(Props(1,'bruno'))
     62res=jackson.toJson(obj)
     63print("result:"+str(res))
     64bson={'Bear': {'props': {'age': 1, 'name': 'bruno'}}}
     65res=jackson.parse(bson, Animal)
     66print("Deserialized an Animal! -->"+str(res))
     67
     68}}}
     69
     70
     71
     72