• 类对象序列化为json串,json串反序列化为类对象


    1.类对象序列化为json

    方法一:

    class P(object):

        def __init__(self,name,age,sex):

            self.name=name

            self.age=age

            self.sex=sex

        def obj_json(self,obj_instance):

            return{

                "name":obj_instance.name,

                "age":obj_instance.age,

                "sex":obj_instance.sex}

    p=P("tom",21,"male")

    print json.dumps(p,default=p.obj_json)

     方法二:

    class P(object):

        def __init__(self,name,age,sex):

            self.name=name

            self.age=age

            self.sex=sex

    p=P("jim",34,"male")

    print p.__dict__

    print json.dumps(p,default=lambda p:p.__dict__)

    print json.dumps(p,default=lambda P:P.__dict__)

    2.json串反序列化为类对象

    class P(object):

        def __init__(self,name,age,sex):

            self.name=name

            self.age=age

            self.sex=sex

    p=P("lucy",21,"female")

    json_str='{"name":"lucy","age":21,"sex":"female"}'

    def jsonToClass(p):

        return P(p["name"],p["age"],p["sex"])

    print json.loads(json_str,object_hook=jsonToClass)

    print p.name

  • 相关阅读:
    Mark
    linux重启mysql无法启动
    网络流量监测IP雷达 4.0
    BBR拥塞控制算法
    弱口令
    SSH加固
    Openstack 部署
    Integrate Neutron and OVN
    Build OpenVSwitch and OVN
    OVN 简单组网脚本
  • 原文地址:https://www.cnblogs.com/reyinever/p/8613582.html
Copyright © 2020-2023  润新知