Python序列化和反序列化 vs JSON

# -*- coding: utf-8 -*
"""没有嵌套类的类

author: Jill

usage:

"""
import json


class Leaf:
    def __init__(self, leaf_arg_a, leaf_arg_b):
        self.leaf_arg_a = leaf_arg_a
        self.leaf_arg_b = leaf_arg_b

    def __str__(self):
        return (
            "Leaf:\n"
            "arg_a: {0.leaf_arg_a}\n"
            "arg_b: {0.leaf_arg_b}\n"
        ).format(self)

    def leaf2dict(self):
        return {
            'leafArgA': self.leaf_arg_a,
            'leafArgB': self.leaf_arg_b
        }

    def dict2leaf(self):
        return Leaf(self['leafArgA'], self['leafArgB'])

    @staticmethod
    def parse_json_obj(json_str):
        a = json.loads(json_str, object_hook=Leaf.dict2leaf)
        return a

    def to_json_str(self):
        return json.dumps(self, default=Leaf.leaf2dict)


if __name__ == '__main__':
    leaf = Leaf("a", "b")
    print(leaf.to_json_str())

    print()

    json_str = '{"leafArgA": "a", "leafArgB": "b"}'
    json_obj = Leaf.parse_json_obj(json_str)
    print(json_obj.leaf_arg_a)
"""有嵌套类Leaf的类

author: Jill

usage:
"""
import json

from entity.child import Leaf


class Root:
    def __init__(self, root_arg_a, leafs):
        self.root_arg_a = root_arg_a
        self.leafs = leafs

    def root2dict(self):
        return {
            'rootArgA': self.root_arg_a,
            'leafs': json.loads(json.dumps(self.leafs, default=Leaf.leaf2dict)),
        }

    def to_json_str(self):
        return json.dumps(self, default=Root.root2dict)

    @staticmethod
    def from_json_obj_get(key, json_str):
        if key == 'leafs':
            json_array = json.dumps(json.loads(json_str).get(key))
            array = json.loads(json_array, object_hook=Leaf.dict2leaf)
            return array
        return json.loads(json_str).get(key)

    @staticmethod
    def parse_json_obj(json_str):
        json_dict = json.loads(json_str)
        root_arg_a = json_dict.get('rootArgA')
        leafs = Leaf.load_from_java(json.dumps(json_dict.get('leafs')))
        return Root(root_arg_a, leafs)


if __name__ == '__main__':
    leaf1 = Leaf('a1', 'b1')
    leaf2 = Leaf('a2', 'b2')
    leafs = [leaf1, leaf2]
    root = Root("root_a", leafs)

    json_obj = root.to_json_str()
    print(json_obj)

    json_str = '{"rootArgA": "root_a", "leafs": ' \
               '[{"leafArgA": "a1", "leafArgB": "b1"}, {"leafArgA": "a2", "leafArgB": "b2"}]}'
    root_obj = Root.parse_json_obj(json_str)
    for leaf in root_obj.leafs:
        print(leaf)

    print(root_obj.root_arg_a)
    leaf_list = Root.from_json_obj_get('leafs', json_str)
    print(leaf_list[0].leaf_arg_a)

 

posted @ 2018-11-23 14:18  JillWen  阅读(306)  评论(0编辑  收藏  举报