I just started working in an environment (Java) that uses Jettison exclusively for marshalling (Object->JSON) and GSON for the unmarshalling (JSON->Object).
I have been having problems unmarshalling JSON objects that were created with the Jettison marshaller. I've noticed that for an object of class X, the jettison produced string is
{"X":{"prop1":"value1", "prop2":"value2"}}
When I try to un-marshal it with GSON, both prop1 and prop2 have null values.
Not trusting the format of the JSON string Jettison produced, I tried to deserialize the string
{"prop1":"value1", "prop2":"value2"}
without the outer JSON wrapper, and GSON treated it correctly.
Is there a way to get Jettison to produce JSON without the outer wrapper attached? Or some way to get Jettison and GSON to work together?
I'm not very familiar with Jettison, but I think it's possible to handle this with GSON.
First of all, we can use GSON's
JsonParserto read the JSON into a tree of elements:Now we want to extract the value of the "X" property of this object. If we know the name of the property, we can just use:
However, from the question it seemed like the name of this property can vary. In this case, we need to dynamically get the first property, for example like this:
Once we have this value, we can deserialize it to an instance of our class as usual: