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?
jackson. databind Description. Basic data binding (mapping) functionality that allows for reading JSON content into Java Objects (POJOs) and JSON Trees ( JsonNode ), as well as writing Java Objects and trees as JSON.
Jackson is a very popular and efficient java based library to serialize or map java objects to JSON and vice versa. This tutorial will teach you basic and advanced Jackson library API features and their usage in a simple and intuitive way.
Open Source - jackson library is open source and is free to use.
Note that Jackson does not use java. io. Serializable for anything: there is no real value for adding that. It gets ignored.
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.
I have the same problem and could not find anything suitable. So I wrote pyson
https://tracinsy.ewi.tudelft.nl/pubtrac/Utilities/wiki/pyson
It's still under development and I will add new features along the way. It's not ment to be a complete substitute for jackson as jackson is huge. I just implement what I need, in jackson style where possible.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With