java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to Specific class

StackOverflow https://stackoverflow.com/questions/22845060

  •  27-06-2023
  •  | 
  •  

Pregunta

I want to have common method for inserting and getting objects from MongoDB collection. For all mongo db operations I am using Jongo library. Here's my code:

 public UserModel getUserByEmailId(String emailId) {
    String query = "{emailId:'"+emailId+"'}";
    Object obj = storage.get(query);

    UserModel user = (UserModel) obj; 
    //getting exception on above line. I am sure that I have UserModel 
    //type of data in obj
    // Exception is: java.lang.ClassCastException: Cannot cast java.util.LinkedHashMap to UserModel
    return user;
}

Here is "storage.get(String query)" method. My intention is to have common method to read data from mongo db. That's why I want it to return Object. (Feel free comment if I'm wrong)

public Object get(String query) {
    Object obj = collection.findOne(query).as(Object.class);
    return obj;
}

//Here: collection is my "org.Jongo.MongoCollection" type object.

What is the right way to get UserModel type of object from "Object"? Let me know if you need more information

¿Fue útil?

Solución

If you only need to map documents to UserModel objects

collection.findOne("{name:'John'}").as(UserModel.class);

If you are looking for a generic approach :

public <T> T get(String query, Class<T> clazz) {
  return collection.findOne(query).as(clazz);
}
...
UserModel user = this.get("{name:'John'}", UserModel.class);

Otros consejos

The Jongo library is returning a map, specifically a LinkedHashMap. You are trying to cast that to an instance of your UserModel class, which Java does not know how to do.

You seem to be expecting the Jongo library to return a UserModel. Assuming that's your custom designed class, there is no way that the library would know how to map the data from MongoDB to this object. Unless of course you could somehow specifically instruct it to do so (I'm not familiar with Jongo).

You could however use Jackson to map the map to UserModel (or other objects).

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top