问题
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") })
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.
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.
Is there some JSON parser available what does the same thing as mentioned above, or I have to follow some different approach for that?
回答1:
I think the most similar option you will get in python ecosystem will be jsonpickle
although it's not as complete as complete Jackson. python engineers and users chose a different respectable perspective and that is using schema-less approaches to problems so typing oriented serialization libraries like Jackson doesn't have a strong equivalent in Python.
回答2:
attrs + cattrs is very close for the task.
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')
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.
来源:https://stackoverflow.com/questions/46214035/what-is-the-alternative-of-jackson-in-python