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