micronautmicronaut-serde

How to deserialize JSON containing mixed types in Micronaut Serde?


Given the following JSON payload:

{
  "thisIs": "trouble",
  "stuff": [
    "string",
    12345,
    {
      "something":"else"
    }
  ]
}

Note the array stuff containing a string, a number and an object.

Here's the POJO we'd be deserializing into:

@Serdeable
class Troublesome {
  private String thisIs;
  // what should `stuff` look like?
}

How should I represent the array of mixed types in the POJO, assuming there could be any number of values of uncertain type?

Is there some way to say "stuff is a JsonArray for parsing later" or "stuff is a String containing the JSON fragment" or something similar?

I would have expected defining stuff to be of type Set<JsonNode> to do the trick, but that fails because there's no bean introspection available for io.micronaut.json.tree.JsonNode. If I go back to using Jackson instead of Serde, this works as expected.


Solution

  • You need to define it as a List<Object> and then implement a custom deserializer that inspects the JsonNode of each list item and when possible delegate the deserialization of an common object types such as String, Number to existing. For custom objects types you need to propagate the class type in order to delegate it to a deserializer.