Nick Otten
Nick Otten

Reputation: 712

Mongo Cannot cast Hashmap to BasicDBObject

I've been working on a java program that makes use of a Mongo database to store certain data about airplanes based on geo coordinates. The application is working to the point as where it is gathering the information and filling up the model objects in the correct way.

When I try to send the object towards the mongo database I get the following error: java.lang.ClassCastException: java.util.hashmap cannot be cast to com.mongodb.basicDbObject. The problem with this exception: I don't have a HashMap (or any type of Map in general)

To add the object to the database I use the following code:

DBCollection table = db.getCollection(GRID_NAME);
GridCell c = cell.getCell(true);
String jString = (String) mapper.writeValueAsString(c); //mapper is a Jackson ObjectMapper
System.out.println(jString);
table.insert((BasicDBObject) JSON.parse(jString));

In here the grid cell contains two floats and a List of Plane objects. The plane object contains one string and another 10 double values. Other then that the classes only have basic getters and setters for all variables.

GridCell

private float lat;
private float lng;
private List<Plane> planeList;

Plane

private String identiefier;
private double minHeight;
private double maxHeight;
private double avgHeight;
private double minSpeed;
private double maxSpeed;
private double avgSpeed;
private double minCourse;
private double maxCourse;
private double avgCourse;

A getter and setter (all look more or less the same as these two)

public float getLng() {
    return lng;
}

public void setLng(float lng) {
    this.lng = lng;
}

As you can see above I'm printing the json string to the console to check if it is correct. I have to admit my plain json reading skills are dodgy at best. But I can't find a hashmap in this:

{"lat":28.0,"lng":5.0,"planeList":[{"identifier":"myTestPlane","minHeight":1.0,"maxHeigh":2.0,"avgHeight":1.5,"minSpeed":1.0,"maxSpeed":2.0,"avgSpeed":1.5,"minCourse":1.0,"maxCourse":2.0,"avgCourse":1.5}]}

Any idea's or suggestions what I'm doing wrong? I might have a Monday morning moment but I really can't figure it out.

Upvotes: 2

Views: 5099

Answers (2)

vambo
vambo

Reputation: 851

Just a heads up that DBObject is not recommended and using Document is encouraged: http://mongodb.github.io/mongo-java-driver/3.1/bson/documents/

Upvotes: 0

Thilo
Thilo

Reputation: 262504

You are using the "wrong" JSON library.

If you want MongoDB's DBObject, you can use com.mongodb.util.JSON.

import com.mongodb.util.JSON;

DBObject bson = ( DBObject ) JSON.parse( json );

If you have an existing Map from somewhere else, you could also try to start with a new BasicDBObject() and putAll the data into it.

Upvotes: 3

Related Questions