I am implementing JSON parsing where I have to talk to a 3rd party API providing JSON over Websocket topic subscriptions. The problem occurs for a set of responses that return JSON in the following basic format:
{
"key_one" : "someEnumString",
"key_two" : "someString",
"key_three" : "someString",
"key_four" : {
"innerKey" : "innerValue"
}
}
I am using Java 8, and GSON 2.8.9 to parse the JSON messages and am looking for insight on how to handle parsing these responses generically.
The issue is as follows: key_four's value 9/10 times is an object of some kind. The remaining 1/10 time, it is a string as follows:
{
"key_one" : "someEnumString",
"key_two" : "someString",
"key_three" : "someString",
"key_four" : "someString";
}
I have defined the 9/10 POJOs needed to deserialize the objects, but do not know how to generically parse these responses so that it handles all of the different objects and a string.
I will know what is in key_four by checking the value of key_one which is actually an enumeration.
Can I get away with using a new Gson() object to deserialize into some class I have defined that somehow knows how to store each possible key_four value type, or do I have to use
JsonParser().parse(jsonString).getAsJsonObject();
and manually parse the data myself?