Search code examples
javajsonhashmapinstanceof

Finding out what type is being used in HashMap


I have a HashMap which is populated from a JSON file. The values in the key-value pair can be of two different types - String or another key-value pair.

For example:

HashMap<String,Object> hashMap = new Map();

The JSON file looks a little something like this:

    "custom": {
       "mappedReference": {"source": "someMappedReference"},
       "somethingElse": "some literal"
     }
    }

Later on after populating hashMap, when I'm iterating through I need to check if the value is of type HashMap or String. I have tried a number of ways but I can't seem to be able to get the type of the object within the Map.

    for(Map.Entry<String,Object> m : hashMap.entrySet())
    {
        final String key = m.getKey();
        final Object value = m.getValue();

        if(value instanceof Map<String,String>) 
        {
            //get key and value of the inner key-value pair...
        }
        else 
        {
            //it's just a string and do what I need with a String.
        }

    }

Any ideas on how I can get the data type from the Map? Thanks in advance


Solution

  • I posted an answer to a similar question: https://stackoverflow.com/a/42236388/7563898

    Here it is:

    It is generally frowned upon to use the Object type unnecessarily. But depending on your situation, you may have to have a HashMap, although it is best avoided. That said if you have to use one, here is a short little snippet of code that might be of help. It uses instanceof.

    Map<String, Object> map = new HashMap<String, Object>();
    
    for (Map.Entry<String, Object> e : map.entrySet()) {
        if (e.getValue() instanceof Integer) {
            // Do Integer things
        } else if (e.getValue() instanceof String) {
            // Do String things
        } else if (e.getValue() instanceof Long) {
            // Do Long things
        } else {
            // Do other thing, probably want error or print statement
        }
    }