earlence earlence - 1 month ago 6
Java Question

GSON deserialize/serialize a json string that has undetermined names of keys

I have JSON like this:

# "trig_cond": {
# "_and": {
# "param1": ["op", "value1"],
# "param2": ["op", "value2"], ...
# },
# "_or": {
# "param1": ["op", "value1"],
# "param2": ["op", "value2"], ...
# }
# }


the "_and"/"_or" part has an undetermined number of keys that map to list objects (each containing two items).
How can I deserialize this into a java object? I've looked at various custom deserialization options but I don't understand how to do it for this example json.

Answer

There are few different options you can take depending on your requirements. One of the simplest solutions you can take when you have an unknown number of keys is to simply leave these parts of your POJO as JSONObject.

For example, this POJO would meet your requirements to deserialize the JSON into a java object, and still provide the flexibility you are after.

public class SamplePojo {
    TrigCond trig_cond;

    public static class TrigCond {
        JsonObject _and;
        JsonObject _or;
    }
}

You could also split them into different files if you prefer.

Also, since in your example, you know what types of values are contained with these param1 and param2 array elements, you could instead using a Map

Here is another example which you may prefer:

public class SamplePojo {
    TrigCond trig_cond;

    public static class TrigCond {
        Map<String, String[]> _and;
        Map<String, String[]> _or;
    }
}

Let me know if I understood your question correctly!