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.

3
  • 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<Object>) ? 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) ? Commented Dec 16, 2021 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). Commented Dec 16, 2021 at 14:39
  • My bad, jumped the gun on closing. Commented Dec 16, 2021 at 17:58

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.