自定义对象转Json:自己探索出来的,直接看下面简单的例子吧。
#自定义对象转换成json
import json
#自定义对象
class C:
key1=list
key2=str
key3=int
key4=tuple
def __init__(self,key1,key2,key3,key4):
self.key1=key1
self.key2=key2
self.key3=key3
self.key4=key4
#实例化自定义类
c=C([1,2,3],'str',0,('yuanzu','元组'))
#json.dumps方法不能对自定义对象直接序列化,首先把自定义对象转换成字典
overdict = c.__dict__
# 此时就可以用json.dumps序列化了
result=json.dumps(overdict, ensure_ascii=False)
print(result)
print(type(result))
二、Json 转自定义对象:暂时查不到 Json 转 Python 对象的傻瓜办法,这里贴一个网友的来自:
https://blog.csdn.net/TaiJi1985/article/details/51344879
发现更简单的办法继续分享。
# 定制类
import time
class D(object):
def __init__(self,map):
self.map = map
def __setattr__(self, name, value):
if name == 'map':
object.__setattr__(self, name, value)
return True
print ('set attr called ',name,value)
self.map[name] = value
def __getattr__(self,name):
v = self.map[name]
if isinstance(v,(dict)):
return (DictObj(v))
if isinstance(v, (list)):
r = []
for i in v:
r.append(DictObj(i))
return (r)
else:
return (self.map[name])
def __getitem__(self,name):
return (self.map[name])
if __name__ == '__main__':
# json转换成字典
import json
#实际上JSON就是Python中的字符串,所以在这里首先定义一个字符串充当从网络请求中得到的json
json_obj='{"key1":[1,2,3],"key2":"str2"}'
# 注意json键值对的边界符只能用双引号
t=json.loads(json_obj)
# 字典转换成自定义对象
model = D(t)
print (model.key2)
三、更新Json转自定义字符串:
import json
class Ook():
name=str
def __init__(self, d):
self.__dict__ = d
if __name__ == '__main__':
data = {'name' : 'ACME','shares' : 100,'price' : {'name' : 'ACME'}}
json_str = json.dumps(data)
result = json.loads(json_str, object_hook=Ook)
print(result.name)
print(result.shares)
print(result.price.name)