0

I've got a little code snippet that's supposed to make parsing JSON arrays simpler. My idea was originally as follows (pseudo-Java):

  public <T> T[] parseAsArray(String content, Class<T> valueType) {
    return objectMapper.readValue(content, T[].class); // doesn't work as you can't just go T[].class
  }

So then I fiddled around with the code. And then some more. And some more.

Eventually I landed at the following mess, which does work, but requires me to create a new array instance, just so I could fetch its array class type, not to mention all the casting.

  public <T> T[] parseAsArray(String content, Class<T> valueType) {
    Class<T[]> tArrClass = (Class<T[]>) Array.newInstance(valueType, 0).getClass();
    return (T[]) objectMapper.readValue(content, tArrClass);
  }

Isn't there a simpler way? All I'm really trying to do is, how can I go from T to T[] and with it to T[].class?

Selbi
  • 813
  • 7
  • 23

0 Answers0