定制Json(反序列化)? [英] Custom Json (de)serialisation?

查看:105
本文介绍了定制Json(反序列化)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一些代码从.Net移植到python.

I'm porting some code from .Net to python.

一方面,我们需要将任意复杂的json从一种格式转换为另一种格式.

At one point, we need to translate arbitrarily complex json from one format to another.

例如:

{"Query": 
    {
        "Boolean": {
            "Operator": "And",
            "Parameters": [
                {"Equal": {"Name": "Bob"}},
                {"Boolean": ...}
            ]
        }
    }
}

致...

{"Query": 
    {
        "Left": {"Name":"Bob"},
        "Right": {...},
        "Operator": "And"
    }
}

我们使用了Json.Net出色的Newtonsoft.Json.JsonConverter来进行序列化/反序列化过程.我们有2个JsonConverter可以将相同的对象与这些格式中的每一个进行转换.

We were using Json.Net's excellent Newtonsoft.Json.JsonConverter to hook into the serialisation / deserialisation process. We have 2 JsonConverters which convert from the same objects to/from each of these formats.

Public Overrides Function CanConvert(objectType As Type) As Boolean
    Return GetType(QueryDefinition).IsAssignableFrom(objectType)
End Function

这意味着我们可以挑选出我们想要手动处理的位,并允许库存转换器执行不需要特别处理的所有属性/值.

This means we can pick out the bits we want to handle manually and allow the stock converter to do all the properties/values that we don't need to treat specially.

Python中是否有任何等效的机制/框架?还是我必须递归地手动解析每个属性?

Is there any equivalent mechanism/framework in Python? or am I going to have to manually parse every property recursively?

推荐答案

您可以继承默认的JSONEncoder.

You can subclass the default JSONEncoder.

来自: http://docs.python.org/2/library/json .html

要使用自定义JSONEncoder子类(例如,一个覆盖default()方法以序列化其他类型的子类),请使用cls kwarg对其进行指定;否则,将使用JSONEncoder."

http://docs.python.org/2/library /json.html#json.JSONEncoder

用法示例: 查看全文

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