Version 3 (modified by 4 years ago) ( diff ) | ,
---|
Packson
Packson is a json (de)serializer for python3 objects. It uses annotations in the style of jackson.
install:
pip install https://tracinsy.ewi.tudelft.nl/pubtrac/Utilities/export/135/packson/dist/packson-1.0.0.tar.gz
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.
A complex example showing many things at once (I did not have time to write out many simpler examples)
from jackson.ObjectMapper import ObjectMapper from jackson.JsonSubTypes import JsonSubTypes from jackson.JsonTypeInfo import JsonTypeInfo from jackson.JsonTypeInfo import Id,As from typing import Dict,List,Set import json class Props: ''' compound class with properties, used for testing ''' def __init__(self, age:int, name:str): if age<0: raise ValueError("age must be >0, got "+str(age)) self._age=age self._name=name; def __str__(self): return self._name+","+str(self._age) def getage(self): return self._age def getname(self): return self._name def __eq__(self, other): return isinstance(other, self.__class__) and \ self._name==other._name and self._age==other._age @JsonSubTypes(["test.ObjectMapperTest.Bear"]) @JsonTypeInfo(use=Id.NAME, include=As.WRAPPER_OBJECT) class Animal: pass class Bear(Animal): def __init__(self, props:Props): self._props=props def __str__(self): return "Bear["+str(self._props)+"]" def getprops(self): return self._props def __eq__(self, other): return isinstance(other, self.__class__) and \ self._props==other._props jackson=ObjectMapper() obj=Bear(Props(1,'bruno')) res=jackson.toJson(obj) print("result:"+str(res)) bson={'Bear': {'props': {'age': 1, 'name': 'bruno'}}} res=jackson.parse(bson, Animal) print("Deserialized an Animal! -->"+str(res))
Note:
See TracWiki
for help on using the wiki.