How to alter Jettison JSON format to exclude outer object wrapper?

547 views Asked by At

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?

1

There are 1 answers

2
andersschuller On

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 JsonParser to read the JSON into a tree of elements:

String json = "{\"X\":{\"prop1\":\"value1\", \"prop2\":\"value2\"}}";
JsonParser parser = new JsonParser();
JsonElement element = parser.parse(json);
JsonObject object = element.getAsJsonObject();

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:

JsonElement value = object.get("X");

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:

Set<Map.Entry<String, JsonElement>> entrySet = object.entrySet();
Map.Entry<String, JsonElement> firstEntry = entrySet.iterator().next();
JsonElement value = firstEntry.getValue();

Once we have this value, we can deserialize it to an instance of our class as usual:

Gson gson = new Gson();
X x = gson.fromJson(value, X.class);
System.out.println(x.prop1);  // prints value1
System.out.println(x.prop2);  // prints value2