0

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

IrishCrf
  • 105
  • 3
  • 13

2 Answers2

1

You can use like below

ParameterizedType pt = (ParameterizedType)Generic.class.getDeclaredField("map").getGenericType();
            for(Type type : pt.getActualTypeArguments()) {
                System.out.println(type.toString());

Ref:How to get value type of a map in Java?

Community
  • 1
  • 1
Pradeep
  • 1,947
  • 3
  • 22
  • 45
1

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
    }
}
Community
  • 1
  • 1
CarManuel
  • 325
  • 3
  • 12
  • I'm just back in work after some a few days off. I was going to post an answer for those who commented with ideas. This is EXACTLY how I figured it out in my own problem above. I'll mark this as the answer. – IrishCrf Feb 20 '17 at 14:16