python中Jackson的替代方法是什么? [英] What is the alternative of Jackson in python?
问题描述
我正在使用 Jackson解析器将Java对象解析为 JSON .我使用以下代码为某些Java对象强加了JSON键.
I am using Jackson parser for parsing for Java object to JSON. I am forcefully adding JSON keys for some java objects, using the following code.
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonSubTypes({ @JsonSubTypes.Type(value = A.class, name = "a"),
@JsonSubTypes.Type(value = F.class, name = "f") })
我在Python中也有相同的set类.我想在python中做同样的事情.但不确定在Python中可用此Jackson注释的替代方法是什么.
I am having same set classes in Python also. I would like to do the same thing in python. But not sure about what are the alternatives for this Jackson annotation available in python.
我的要求是我必须向REST API发送POST请求.我需要将Java对象序列化为JSON.但是由于我的类结构有些不同,所以我没有在Java类中方便地提到所有JSON键.为了解决这个问题,我正在做的是在JSON中找到从Java传递来的"A"对象时,在JSON中添加了"a"键.它对"F"对象做同样的事情.因此,我已经按照上面提到的方式实现了解决方案.我想在Python中实现相同的目的.
My requirement is that I have to send a POST request to a REST API. I need to serialize the java object into JSON. But as my class structure is a little bit different I don't have all the JSON keys mentioned handy in java classes. To solve the issue what I am doing is that I am adding 'a' key in JSON when it finds 'A' object is passed from java. It is doing the same thing for 'F' object. So, I have achieved the solution the way I mentioned above. I want to achieve the same thing in Python.
是否存在一些可用的JSON解析器,或者我必须遵循一些不同的方法?
Is there some JSON parser available what does the same thing as mentioned above, or I have to follow some different approach for that?
推荐答案
attrs + cattrs is very close for the task.
在此处复制一个cattr示例,
copy one cattr example here,
>>> import attr, cattr
>>>
>>> @attr.s(slots=True, frozen=True) # It works with normal classes too.
... class C:
... a = attr.ib()
... b = attr.ib()
...
>>> instance = C(1, 'a')
>>> cattr.unstructure(instance)
{'a': 1, 'b': 'a'}
>>> cattr.structure({'a': 1, 'b': 'a'}, C)
C(a=1, b='a')
但是它不如Jackson强大,我还没有找到在序列化json和反序列化python对象之间映射属性的解决方案.
but it's not as capable as Jackson, i've not yet been able to find a solution to map attribute between serialized json and deserialized python object.
这篇关于python中Jackson的替代方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!