@ Override public Hashtable < String , Object > getDataAsHashtable ( ) { Preconditions . checkArgument ( resource != null , "File resource cannot be null" ) ; logger . entering ( ) ; // Over-writing the resource because there is a possibility that a user // can give a type resource . setCls ( Hashtable [ ] . class ) ; Hashtable < String , Object > dataAsHashTable = null ; JsonReader reader = null ; try { reader = new JsonReader ( getReader ( resource ) ) ; Object [ ] [ ] dataObject = mapJsonData ( reader , resource . getCls ( ) ) ; dataAsHashTable = new Hashtable <> ( ) ; for ( Object [ ] currentData : dataObject ) { // Its pretty safe to cast to array and its also known that a 1D // array is packed Hashtable < ? , ? > value = ( Hashtable < ? , ? > ) currentData [ 0 ] ; /* * As per the json specification a Json Object is a unordered collection of name value pairs. To give * out the json data as hash table , a key needs to be figured out. To keep things clear and easy the * .json file must have all the objects with a key "id" whose value can be used as the key in the * hashtable.Users can directly access the data from the hash table using the value. * * Note: The id is harcoded purposefully here because to enforce the contract between data providers to * have common methods. */ dataAsHashTable . put ( ( String ) value . get ( "id" ) , currentData ) ; } } catch ( NullPointerException n ) { // NOSONAR throw new DataProviderException ( "Error while parsing Json Data as a Hash table. Root cause: Unable to find a key named id. Please refer Javadoc" , n ) ; } catch ( Exception e ) { throw new DataProviderException ( "Error while parsing Json Data as a Hash table" , e ) ; } finally { IOUtils . closeQuietly ( reader ) ; } logger . exiting ( dataAsHashTable ) ; return dataAsHashTable ; }
A utility method to give out JSON data as HashTable . Please note this method works on the rule that the json object that needs to be parsed MUST contain a key named id .