0

I have a JSON array like this:

[
  "0",
  {
    "number": 1,
    "field": "value"
  },
  {
    "number": 2,
    "field": "value"
  }
]

The first element to the array is a string.

Is it possible to deserialize it with FasterXML Jackson?

I know how to do it with different objects.
I need to use @JsonSubTypes (Here is an example https://stackoverflow.com/a/38877862/2564509)

The problem with this array is that the first element is String type.

João Dias
  • 16,277
  • 6
  • 33
  • 45
djm.im
  • 3,295
  • 4
  • 30
  • 45
  • 1
    I'm not set up to test it, but the "only" issue I see compared to the linked solution, is that String is final and can not be made to extend a custom interface. But 1) do you really need a single, custom interface (e.g. List) ? 2) What about creating a StringWrapper class that holds a String (maybe with a custom (De)Serializer ? 3) What about cheating by extending something not final and String-like, e.g. a CharSequence implementation (sadly, StringBuilder is final too) ? – GPI Dec 16 '21 at 14:26
  • @GPI Yes, the String class is final. Because of that, I cannot have a common interface for String and other classes. 1) I get an array from an API like in the question. I cannot change it. 2) I haven't tried it. So this is the next to try. 3) For my case, it is not a good approach because other elements (objects) are not String-related (they are more specific, like user data). – djm.im Dec 16 '21 at 14:39
  • My bad, jumped the gun on closing. – DwB Dec 16 '21 at 17:58

1 Answers1

2

Caveat: Your situation is an unfortunate edge case. As such, the solution is likely to be not wonderful.

This works, but is not wonderful:

  1. First, deserialize as a List<Object>. In your case, this will result in a List of three elements; String, LinkedHashMap, and LinkedHashMap
  2. Next, process each element in the array and, process based on the element type; a String will be your String element, a LinkedHashMap will be the representation of your number-field class.
DwB
  • 37,124
  • 11
  • 56
  • 82