| 271 | An example using custom (de)serializer comes from DeserializerTest.py: |
| 272 | |
| 273 | {{{ |
| 274 | class ValueDeserializer(Deserializer): |
| 275 | def __hash__(self): |
| 276 | return hash(self.geta()) |
| 277 | def deserialize(self, data:object, clas: object)-> object: |
| 278 | if type(data)!=str: |
| 279 | raise ValueError("Expected str starting with '$', got "+str(data)) |
| 280 | return Simple(int(data[1:])) |
| 281 | |
| 282 | class ValueSerializer(Serializer): |
| 283 | def serialize(self, obj:object)-> object: |
| 284 | if not isinstance(obj, Simple): |
| 285 | raise ValueError("Expected Dimple object") |
| 286 | return "$" + str(obj.geta()) |
| 287 | |
| 288 | |
| 289 | @JsonDeserialize("test.DeserializerTest.ValueDeserializer") |
| 290 | @JsonSerialize("test.DeserializerTest.ValueSerializer") |
| 291 | class Simple: |
| 292 | def __init__(self, a:int): |
| 293 | self._a=a |
| 294 | def geta(self)->int: |
| 295 | return self._a |
| 296 | def __eq__(self, other): |
| 297 | return isinstance(other, self.__class__) and \ |
| 298 | self._a==other._a |
| 299 | def __repr__(self): |
| 300 | return "Simple:"+str(self._a) |
| 301 | def __hash__(self): |
| 302 | return hash(self._a) |
| 303 | |
| 304 | pyson.toJson(Simple(12)) |
| 305 | pyson.parse("$12", Simple) |
| 306 | |
| 307 | }}} |
| 308 | |
| 309 | |