0

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?

Zander
  • 13
  • 4
  • 1
    Is `"key_four"` a fixed member name, or can its name vary? Or rather, do you have a data class with `key_four` as field or are you deserializing this as `Map`? Can `key_four` only have one specific non-String value, or could if have (depending on the `key_one` value) multiple different JSON object values, each with different members? – Marcono1234 Jun 17 '22 at 22:17
  • @Marcono1234 it will always be called "key_four." It's value will be either a string representing a time, or otherwise it will be one of 9 different objects that are completely different from each other (and as you said, identifiable by the key_one value) – Zander Jun 18 '22 at 23:25
  • Maybe the answers to https://stackoverflow.com/q/15736654 might be helpful in your case. Unfortunately Gson does not offer deserialization of polymorphic types out of the box. If you have not settled on Gson yet, you could also give Jackson a try which has support for polymorphic deserialization. – Marcono1234 Jun 21 '22 at 21:01
  • @Marcono1234 thank you very much for your assistance. I believe that sent me down a path that allowed me to "rubber ducky" a solution. – Zander Jun 27 '22 at 13:52

0 Answers0