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?

8
  • I think that you can use TypeToken (or something like that) to specify that the result will be of List<T>. Commented Sep 16, 2020 at 10:16
  • i found it new TypeReference<List<T>>() No idea how to deal with arrays., Commented Sep 16, 2020 at 10:17
  • here you have some string->class hax stackoverflow.com/a/44720865/1527544 Commented Sep 16, 2020 at 10:19
  • Pass in a Class<T[]>? e.g. parseAsArray(someContent, Integer[].class)? Commented Sep 16, 2020 at 10:26
  • Class<T[]> arrayClass = (Class<T[]>) Class.forName("[L" + classOnWhichArrayIsDefined.getName() + ";"); seems even more messy, not really what I had in mind... Commented Sep 16, 2020 at 10:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.