Converting Object to Map: Cast vs ObjectMapper

6324 :

What is the difference between below two methods of converting Object to Map? And which method is better, assuming both methods work for converting an Object to a Map?

Cast:

Object o = some object;
Map<String, Object> map = (Map<String, Object>) o;

ObjectMapper:

Object o = some object;
Map<String, Object> map = new ObjectMapper().readValue((String) o, new TypeReference<Map<String, Object>>() {});
xingbin :

That's depends what the input is.

  • (Map<String, Object>) o is used for casting conversion, so the runtime type of o must be Map, otherwise ClassCastException will be thrown:

    Object o = new HashMap<>();
    Map<String, Object> map = (Map<String, Object>) o; // ok
    
    Object o = new ArrayList<>();
    Map<String, Object> map = (Map<String, Object>) o; //ClassCastException
    
    Object o = new String();
    Map<String, Object> map = (Map<String, Object>) o; //ClassCastException
    
  • ObjectMapper().readValue(String content, JavaType valueType):

    Method to deserialize JSON content from given JSON content String.

    which means the input should be a String in valid json format. For example:

    Object input = "{\"key1\":{},\"key2\":{}}";
    Map<String, Object> map = new ObjectMapper().readValue((String) input, new TypeReference<Map<String, Object>>() {});
    
    System.out.println(map.size()); // 2
    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=79805&siteId=1