是否有一个python json库可以将json转换为模型对象,类似于google-gson? [英] Is there a python json library can convert json to model objects, similar to google-gson?

查看:161
本文介绍了是否有一个python json库可以将json转换为模型对象,类似于google-gson?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标准的python json模块只能将json字符串转换为dict结构.

The standard python json module only can convert json string to dict structures.

但是我更喜欢将json转换为具有其父子"关系的模型对象结构.

But I prefer to convert json to a model object strutures with their "parent-child" relationship.

我在Android应用中使用google-gson,但不知道哪个python库可以做到这一点.

I use google-gson in Android apps but don't know which python library could do this.

推荐答案

您可以让json模块构造一个字典,然后使用字典成一个对象,就像这样:

You could let the json module construct a dict and then use an object_hook to transform the dict into an object, something like this:

>>> import json
>>>
>>> class Person(object):
...     firstName = ""
...     lastName = ""
...
>>>
>>> def as_person(d):
...     p = Person()
...     p.__dict__.update(d)
...     return p
...
>>>
>>> s = '{ "firstName" : "John", "lastName" : "Smith" }'
>>> o = json.loads(s, object_hook=as_person)
>>>
>>> type(o)
<class '__main__.Person'>
>>>
>>> o.firstName
u'John'
>>>
>>> o.lastName
u'Smith'
>>>

这篇关于是否有一个python json库可以将json转换为模型对象,类似于google-gson?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆