定制Json(反序列化)? [英] Custom Json (de)serialisation?
问题描述
我正在将一些代码从.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 JsonConverter
s 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
用法示例: 查看全文