json - Convert JSONArray to appropriately-typed Java array -


i'm struggling @ integrating existing pieces of code server accepts inputs via json payload. handed json object, , need construct map represents key-value pairs, values take on reasonable, expected types. org.json parser seems adequate every case except 1 around jsonarrays.

i can see it's quite easy build string[] jsonarray ... provided know string[] need. however, handed arrays of doubles, arrays of ints, nothing distinguish them. need figure out type, , create appropriately-typed array.

i've tried pulling first element array , getting type, in hopes of creating array instance of type, so:

private object[] decodetoarray(jsonarray list) throws jsonexception {       if (list.length() > 0) {         class<? extends object> type = list.get(0).getclass();         type[] result = array.newinstance(type, list.length());     } 

but of course, doesn't compile -- type instance, not class; won't accept ? type; , if try give name, la <t extends object>, requires t declared in method signature, doesn't seem connected in way unknown type obtained list element.

and this, of course, doesn't @ int[] , double[] case. integer[] , double[] acceptable compromises, probably.

as interim solution, i've been able render jsonarray object[], , change server-side code interacts these arrays cast them needed, it's ugly, , allows json-yuck seep our code base.

are there libraries or clever tricks creating arrays of unknown type in java? there json convention can ask used inform me type expected?

assuming real world , not homework, use gson, library you're looking for.

also, read thread thoroughly: https://stackoverflow.com/questions/338586/a-better-java-json-library?rq=1


Comments

Popular posts from this blog

linux - Does gcc have any options to add version info in ELF binary file? -

android - send complex objects as post php java -

charts - What graph/dashboard product is facebook using in Dashboard: PUE & WUE -