| 1 | == Packson |
| 2 | |
| 3 | Packson is a json (de)serializer for python objects. |
| 4 | It uses annotations in the style of jackson. |
| 5 | |
| 6 | |
| 7 | The 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 | |
| 9 | A complex example showing many things at once (I did not have time to write out many simpler examples) |
| 10 | |
| 11 | {{{ |
| 12 | from jackson.ObjectMapper import ObjectMapper |
| 13 | from jackson.JsonSubTypes import JsonSubTypes |
| 14 | from jackson.JsonTypeInfo import JsonTypeInfo |
| 15 | from jackson.JsonTypeInfo import Id,As |
| 16 | from typing import Dict,List,Set |
| 17 | import json |
| 18 | |
| 19 | class 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) |
| 41 | class Animal: |
| 42 | pass |
| 43 | |
| 44 | |
| 45 | class 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 | |
| 58 | jackson=ObjectMapper() |
| 59 | |
| 60 | |
| 61 | obj=Bear(Props(1,'bruno')) |
| 62 | res=jackson.toJson(obj) |
| 63 | print("result:"+str(res)) |
| 64 | bson={'Bear': {'props': {'age': 1, 'name': 'bruno'}}} |
| 65 | res=jackson.parse(bson, Animal) |
| 66 | print("Deserialized an Animal! -->"+str(res)) |
| 67 | |
| 68 | }}} |
| 69 | |
| 70 | |
| 71 | |
| 72 | |