Python实现JSON反序列化类对象

咱们的网络协议通常是把数据转换成JSON以后再传输。以前在Java里面,实现序列化和反序列化,不论是jackson,仍是fastjson都很是的简单。如今有项目须要用Python来开发,很天然的但愿这样的便利也能在Python中体现。java

可是在网上看了一些教程,讲反序列化的时候,基本都是转换为dict或者array。这种编程方式我从情感上是没法接受的。难道是这些JSON库都不支持反序列化为类对象?我立刻打消了这个念头,Python这样强大的脚本语言,不可能没有完善的JSON库。编程

因而我就研究了一下原生的json,以及第三方的demjsonsimplejsonjson

1、原生json

我仔细研究了原生jsonloads方法的定义bash

def loads(s, encoding=None, cls=None, object_hook=None, parse_float=None, parse_int=None, parse_constant=None, object_pairs_hook=None, **kw)
复制代码

这里面的object_hookobject_pairs_hook参数引发了个人注意,我重点说一下object_hook网络

官方文档的说明以下:数据结构

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict. This feature can be used to implement custom decoders (e.g. JSON-RPC class hinting).函数

这个object_hook根据文档的解释就是一个自定义解码函数,入参数标准反序列化后的dict,咱们能够根据本身的规则转换输出为想要的格式。post

我又去搜了一下object_hook,你们对于这个东西的处理方式基本就是用一个静态方法把dict转换成对象。测试

咱们的数据结构是这样的ui

{"status":1,"info":"发布成功","data":{"id":"52","feed_id":"70"}}
复制代码

因而我就写了这样的代码:

class Response:

    def __init__(self, status, info, data) -> None:
        super().__init__()
        self.status = status
        self.info = info
        self.data = data

    @staticmethod
    def object_hook(d):
        return Response(d['status'], d['info'], d['data'])
 ...
resp = json.loads(body, object_hook=Response.object_hook)
复制代码

一开始呢,确实没有问题,虽然用起来没有java的json库辣么方便,但总归实现了需求。

好景不长,我测试的第一个接口返回的数据中,data是字段一个字符串,反序列化正常。但是后来当接口返回的结构中data字段是一个dict结构的时候,object_hook的入参竟然变成了data字段转换以后的dict({"id":"52","feed_id":"70"}),而不是完整的数据。

这些懵逼了,上网搜索了一圈没有结论。好吧,我最后又老老实实回到官方文档,read the fucking official document

不看不知道,一看吓一跳,官方文档用了一种巧妙的方式实现了上面的需求。

>>> class JSONObject:
...     def __init__(self, d):
...         self.__dict__ = d
...
>>>
>>> data = json.loads(s, object_hook=JSONObject)
>>> data.name
'ACME'
>>> data.shares
50
>>> data.price
490.1
>>>
复制代码

我服了,把json解析以后的dict直接赋值给对象的属性dict,而后就能够为所欲为的使用属性了,真心方便,动态语言就是好。

以上是官方的json库实现方案,那另外两个知名的第三方库呢?

2、demjson

demjson也支持hook。有两种配置的方式:decode函数配置和set_hook函数配置

1. decode

def decode( txt, encoding=None, **kwargs )
复制代码

decode函数能够指定不少参数,其中就包括hook函数。hook函数的指定是使用键值对的方式,键是hook函数的名称,值是hook函数。

demjson是经过名字来管理hook函数的,因此hookname不是随便指定的,必须是内置的几种hook函数的名称。

  • decode_number
  • decode_float
  • decode_object
  • decode_array
  • decode_string
  • encode_value
  • encode_dict
  • encode_dict_key
  • encode_sequence
  • encode_bytes
  • encode_default
demjson.decode(body, encode='utf-8',decode_obbject=Reponse.object_hook)
复制代码

结果并无让我很开森,依然是没法处理嵌套结构。 日志中显示以下内容:

2018-01-30 16:01:17,137 poster.py post_all 73 INFO    : {"status":1,"info":"\u53d1\u5e03\u6210\u529f","data":{"id":"54","feed_id":"72"}}
2018-01-30 16:01:17,138 response.py object_hook 13 INFO    : {'id': '54', 'feed_id': '72'}
2018-01-30 16:01:17,138 response.py object_hook 13 INFO    : {'status': 1, 'info': '发布成功', 'data': demjson.undefined}
复制代码

很奇怪的是object_hook 函数被调用了两次,第一次是data字段的内容,第二是所有的内容,可是data字段没有解析出来。 很是奇怪,百思不得其解!!!

2. set_hook

set_hook函数跟上面的decode函数不同,它是JSON类的成员函数,而decode函数是个静态函数。

def set_hook(self, hookname, function)
复制代码

吸收以前的教训,此次我仔细阅读了demjson的文档,还真发现点东西。

Netsted values. When decoding JSON that has nested objects or arrays, the decoding hooks will be called once for every corresponding value, even if nested. Generally the decoding hooks will be called from the inner-most value outward, and then left to right.

这里重点说到嵌套的问题,出现嵌套的时候,每一个对应的类型都会调用hook函数一次,并且是从最内层,从左往右。好吧,以前出现的问题所有明白了,原来都是这个规则惹的祸,可是为何这样设计我暂时仍是不明白。

set_hook的使用方式

j = demjson.JSON()
    j.set_hook( 'decode_array', my_sort_array )
    j.decode(body, encode='utf-8')
复制代码

3、simplejson

前面说了那么多,simplejson的方式就没什么可说的,跟官方的jsonhook方式一致。

总结

虽然个人需求是知足了,可是仍是有一个大大的问号留在我心中,为何是这样设计,网上没有找到合适的答案,剩下的须要研究源代码分析了。

相关文章
相关标签/搜索