1 3
import json
2

3 3
from mopidy.models import immutable
4

5

6 3
class ModelJSONEncoder(json.JSONEncoder):
7

8
    """
9
    Automatically serialize Mopidy models to JSON.
10

11
    Usage::
12

13
        >>> import json
14
        >>> json.dumps({'a_track': Track(name='name')}, cls=ModelJSONEncoder)
15
        '{"a_track": {"__model__": "Track", "name": "name"}}'
16

17
    """
18

19 3
    def default(self, obj):
20 3
        if isinstance(obj, immutable.ImmutableObject):
21 3
            return obj.serialize()
22 0
        return json.JSONEncoder.default(self, obj)
23

24

25 3
def model_json_decoder(dct):
26
    """
27
    Automatically deserialize Mopidy models from JSON.
28

29
    Usage::
30

31
        >>> import json
32
        >>> json.loads(
33
        ...     '{"a_track": {"__model__": "Track", "name": "name"}}',
34
        ...     object_hook=model_json_decoder)
35
        {u'a_track': Track(artists=[], name=u'name')}
36

37
    """
38 3
    if "__model__" in dct:
39 3
        model_name = dct.pop("__model__")
40 3
        if model_name in immutable._models:
41 3
            cls = immutable._models[model_name]
42 3
            return cls(**dct)
43 3
    return dct

Read our documentation on viewing source code .

Loading